Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA 2.1 Foreign Key isn't saving on ManyToOne cascade

I have two classes.

public class Reservation {
    @OneToMany(cascade = CascadeType.ALL, orphanRemoval=true, mappedBy = "reservation")
    private List<Night> nights;  \\assume getters and setters
}

public class Night {
    @ManyToOne
    @JoinColumn(name = "RESERVATION_ID")
    private Reservation reservation;
}

My save works like this:

Reservation r = new Reservation();
r.getNights().add(new Night()); 
return dao.save(r);

This works, as in it saves the Reservation, and it saves the Night. But when I look at the database, the column RESERVATION_ID in the NIGHT table is null.

In previous projects (before upgrading to Java 8 and JPA 2.1), I didn't need to manually set the parent object on the child in order for that association to save. Did something change, or am I doing something wrong?

Edit:

This saves the association correctly, but it didn't used to be necessary.

Reservation r = new Reservation();
Night n = new Night();
n.setReservation(r);
r.getNights().add(n);
return dao.save(r);
like image 941
Risu Avatar asked Nov 10 '22 04:11

Risu


1 Answers

According to JPA example provided in link below, you need to set the parent object in the child. You can do it in the Parent class (child's getter method)

http://en.wikibooks.org/wiki/Java_Persistence/OneToMany

like image 179
pms Avatar answered Nov 14 '22 23:11

pms