使用 MyBatis 将集合持久保存在对象中

发布于 2024-10-04 05:24:42 字数 1058 浏览 4 评论 0原文

我有 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

[旋木] 2024-10-11 05:24:42

尽管 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文