开发者

Inserting child objects in MyBatis

开发者 https://www.devze.com 2023-02-06 06:55 出处:网络
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 de开发者_StackOverflow社区tails), how do I write code to be

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 de开发者_StackOverflow社区tails), 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};
        

        
        



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.

0

精彩评论

暂无评论...
验证码 换一张
取 消