I have a general question about Hibernate that I'm batteling with.
I have class A and class B, where B is dependent on A
In my code when I call em.persist(objOfTypeA) I would expect the insert to go and insert into both tables AAA and BBB. If I manually presist A get A's ID and fill it in the list for each object and then persist that list, things are working. But I would expect this to happen magically by Hibernate.
Am I doing something wrong? Or am I just expecting too much of Hibernate?
Thanks
@Entity
@Table(name = "AAA")
@Veto
public class A {
@Id
@GeneratedValue
@Column(name = "Id")
private Long id;
@NotNull
@Column(name = "Name")
private Long name;
...
@OneToMany(mappedBy="a", fetch=FetchType.LAZY, cascade={CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE})
private List<B> b;
...
}
@Entity
@Table(name = "BBB")
@Veto
public class B {
@Id
@GeneratedValue
@Column(name="Id")
private Long id;
@NotNull
@Column(name="AId")
private Long aId;
@NotNull
@Column(name = "Name")
private Long name;
@JoinColumn(name = "AId", referencedColumnName="Id", updatable = false, insertable = false)
@ManyToOne(optional = false)
private A a;
...
}
I finally worked it out. None of the examples I was given or found told me exactly what was wrong, it was only after my own experimentation that I managed to come to this conclusion:
Instead of having
@OneToMany(mappedBy="a", fetch=FetchType.LAZY, cascade={CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE})
private List<B> b;
that didn't work (FK was still coming as NULL)
This did work:
@OneToMany(fetch=FetchType.LAZY, cascade={CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE})
@JoinColumn(name="AId")
@NotNull
private List<B> b;