在MyBatis中插入子对象 [英] Inserting child objects in MyBatis

查看:1330
本文介绍了在MyBatis中插入子对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的对象图,我想使用MyBatis存储在数据库中。如果我创建一个全新的对象图(带有两个细节的BatisNode),如何编写代码以确保创建子对象?以下是详细信息:

I have a very simple object graph that I want to store in a database using MyBatis. If I make a brand new object graph (a BatisNode with two details), how do I write code to be sure the child objects are created? Here are the details:



public class BatisNode {
    protected int id;
    protected List details;
    protected String name;
        //Constructor and getters.
}

public class BatisNodeDetail {
    protected int id;
    protected BatisNode parent;
    protected String name;
        //Constructor and getters.
}

架构:


CREATE TABLE node (
    node_id int auto_increment primary key,
    name varchar(255)
);

CREATE TABLE node_detail(
    node_detail_id int auto_increment primary key,
    name varchar(255)
);

Mapper:


    
        
INSERT INTO node (
  name
)
SELECT #{name};
        

        
SELECT node_id id,
name
FROM node
WHERE node_id=#{id};
        

        
        



推荐答案

Ibatis / Mybatis不是一个ORM,只是一个DataMapper,简单/限制特别在这些场景中显示(对象图):它(基本上)不知道对象的图形。

Ibatis/Mybatis is not an ORM, just a DataMapper, and that simplicity/limitations shows specially in these scenarios (graph of objects) : it (basically) doesn't know about graph of objects.

我采取的一种方法是:

我有:


  1. 一层轻量级POJO对象(DTO对象),每个对应一个数据库表(一个对象< - >一个db表的记录),它们有只有属性(比如你的BatisNode和BatisNodeDetail示例)

  1. a layer of lightweight POJO objects ("DTO objects"), each corresponds to a database table (one object <-> one record of a db table), they have little more than properties (like your BatisNode and BatisNodeDetail examples)

DAO层,每个DTO(例如,BatisNodeDAO和BatisNodeDetailDAO)的一个服务对象与数据源注入,标准insert / loadById / delete和select方法( iBator 可以帮到你)

a DAO layer, one service object for each DTO (say, BatisNodeDAO and BatisNodeDetailDAO) with the datasource injected, and the standard insert/loadById/delete and select methods (iBator can help you here)

服务层,是具有典型服务类(通常是单例)的双方还定义了一些重量级对象(域对象),它们通常对应于DTO对象的图形(在您的示例中为BatisNodeWithDetails)。这些域对象知道如何加载/保存包装DTO的图形,调用DAO(以及处理事务,检测脏对象等)。请注意,对于不同的服务方法或用例,可能有几个域类包含相同的DTO(也就是说,不同的图形)。

the service layer, besides having the typical service classes (singletons normally), defines also some heavyweight objects, ("domain objects"), which they deal with, and which typically correspond to a graph of DTO objects (in your example, a BatisNodeWithDetails). These domain objects know how to load/save the graph of wrapped DTOs, calling the DAOs (and taking care of transactions, detection of "dirty" objects, etc). Notice that there can be several "domain classes" that wrap a same DTO (that is to say, distinct graphs), for different service methods or use cases.

这篇关于在MyBatis中插入子对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆