Persist collection in object with MyBatis

无人久伴 提交于 2019-12-01 01:15:53

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/4287544/persist-collection-in-object-with-mybatis

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!