在MyBatis的对象中持久化集合 [英] Persist collection in object with 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
}
创建一张票和一些地方:
Then I create one ticket and some places:
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);
现在我想把它保存到DB:
And now I want to save it to DB:
session.insert("insertTicket", ticket);
session.commit();
在MapperConfig.xml中,我写这行:
In MapperConfig.xml I write this lines:
<insert id="insertTicket" parameterType="Ticket">
INSERT INTO tickets (cost, time) VALUES (#{cost}, #{time})
</insert>
如何以自动模式保存列出地点?
MyBatis可以为我保存吗?
或者我需要用 foreach 手动迭代,并手动插入 Place ?
How I can save List places in automatic mode? Does MyBatis can save it for me? Or I need to iterate manually with foreach and insert every Place by hand?
任何帮助。
推荐答案
尽管MyBatis能够支持相反的方向(即在查询期间填充列表,或从连接),则不存在将包含列表插入数据库的自动模式。
Even though MyBatis is able to support the reverse direction (i.e. filling the list during a query with a nested select or from a join), there is no automatic mode that inserts the containing list into the database.
根据此 Google网上论坛讨论,您必须手动插入列表元素。
According to this Google Groups discussion you have to insert the list elements manually.
这篇关于在MyBatis的对象中持久化集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!