Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Persist collection in object with MyBatis

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.

like image 751
swap_i Avatar asked Nov 26 '10 17:11

swap_i


1 Answers

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.

like image 82
vanje Avatar answered Oct 02 '22 22:10

vanje