使用MyBatis在对象中保留集合

swa*_*p_i 8 java sql collections persistence mybatis

我有POJO课程:

class Ticket {
    private int id;
    private double cost;
    private Date time;
    private List<Place> places;

    // Getters and setters here
}

class Place {
    private int row;
    private int place;

    // Getters and setters here
}
Run Code Online (Sandbox Code Playgroud)

然后我创建一张票和一些地方:

Ticket ticket = new Ticket();
ticket.setCost(58.7);
ticket.setTime(new Date());

Place place1 = new Place();
place1.setRow(1);
place1.setPlace(2);
ticket.addPlace(place1);

Place place2 = new Place();
place2.setRow(3);
place2.setPlace(4);
ticket.addPlace(place2);
Run Code Online (Sandbox Code Playgroud)

现在我想将它保存到DB:

session.insert("insertTicket", ticket);
session.commit();
Run Code Online (Sandbox Code Playgroud)

在MapperConfig.xml中,我写这行:

<insert id="insertTicket" parameterType="Ticket">
    INSERT INTO tickets (cost, time) VALUES (#{cost}, #{time})
</insert>
Run Code Online (Sandbox Code Playgroud)

如何在自动模式下保存列表位置?MyBatis可以为我保存吗?或者我需要手动迭代foreach并手动插入每个地方

谢谢你的帮助.

van*_*nje 10

即使MyBatis能够支持反向(即在使用嵌套选择或来自连接的查询期间填充列表),也没有将包含列表插入数据库的自动模式.

根据此Google网上论坛的讨论,您必须手动插入列表元素.

  • MyBatis实际上是_is_聪明.但它并不打算成为ORM.它只是作为JDBC的瘦包装器.如果需要此功能,那么您可以查找像Hibernate http://www.hibernate.org/或EclipseLink http://www.eclipse.org/eclipselink/这样的ORM. (7认同)