使用 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
}
然后我创建一张票证和一些位置:
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);
现在我想将其保存到数据库:
session.insert("insertTicket", ticket);
session.commit();
在 MapperConfig.xml 中,我编写以下几行:
<insert id="insertTicket" parameterType="Ticket">
INSERT INTO tickets (cost, time) VALUES (#{cost}, #{time})
</insert>
如何在自动模式下保存列出位置? MyBatis 可以帮我保存吗? 或者我需要使用 foreach 手动迭代并手动插入每个 Place ?
感谢您的任何帮助。
I have POJO classes:
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);
And now I want to save it to DB:
session.insert("insertTicket", ticket);
session.commit();
In MapperConfig.xml I write this lines:
<insert id="insertTicket" parameterType="Ticket">
INSERT INTO tickets (cost, time) VALUES (#{cost}, #{time})
</insert>
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?
Thanks for any help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尽管 MyBatis 能够支持反向(即在查询期间使用嵌套选择或连接填充列表),但没有自动模式将包含列表插入数据库。
根据此 Google 网上论坛讨论,您必须插入手动列出元素。
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.
According to this Google Groups discussion you have to insert the list elements manually.