5

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);
Risu
  • 796
  • 2
  • 14
  • 26
  • Thank you for your link, however I don't see how it helps answer my question. It is a bidirectional relationship, as I show in the code. – Risu Jul 22 '14 at 21:11
  • it was back to your question `Did something change, or am I doing something wrong?` So the answer is, you are not missing. That's the way it should be implemented. However you can make it unidirectional and add/remove them separately. That's your choice (AFAIK). – pms Jul 22 '14 at 21:34
  • Forgive my confusion, but are you saying `r.getNights().add(new Night());` (before the edit) should work to save the association? – Risu Jul 22 '14 at 21:45
  • Sorry my bad. Yes you need to set the parent object in the child. You can do it in the Parent class (child's getter method). – pms Jul 22 '14 at 21:49
  • Alright, so after the edit is how it's supposed to be, and before the edit was just some auto-magic that I shouldn't have been relying on. Correct? – Risu Jul 22 '14 at 21:51
  • Sorry I didn't get your question. – pms Jul 22 '14 at 21:54
  • To clarify: I've been doing it wrong. Right? – Risu Jul 22 '14 at 21:56
  • right. Was that working in your previous project? Because AFAIK it shouldn't work properly. – pms Jul 22 '14 at 21:59
  • Yes, but that was JPA 1 and Hibernate 3. – Risu Jul 22 '14 at 22:00
  • Thank you for your help. Did you want to write up an answer that I can accept so you can get points? – Risu Jul 22 '14 at 22:01

1 Answers1

1

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

pms
  • 944
  • 12
  • 28