问题
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;
...
}
回答1:
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;
回答2:
Modify the mapping of class B
as below,
@Entity
@Table(name = "BBB")
@Veto
public class B {
@Id
@GeneratedValue
@Column(name="Id")
private Long id;
@NotNull
@Column(name="AId", updatable = false, insertable = false)
private Long aId;
@NotNull
@Column(name = "Name")
private Long name;
@JoinColumn(name = "AId", referencedColumnName="Id")
@ManyToOne(optional = false)
private A a;
...
}
You were using the attributes updatable = false, insertable = false
at wrong place and I have corrected it.
Read here to understand how they works.
来源:https://stackoverflow.com/questions/9443540/hibernate-cascade-persist