Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

        
        


See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
121 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...