Inserting child objects in MyBatis

南笙酒味 提交于 2019-12-09 04:57:27

问题


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.
}

Schema:

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};
        

        
        



回答1:


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.

One approach I've taken is this:

I have:

  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)

  2. 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)

  3. 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.



来源:https://stackoverflow.com/questions/4788886/inserting-child-objects-in-mybatis

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!