I have the following 2 entites:
@Entity
@Table(name = "PARENT")
public class ParentEntity{
@Id
@Column(name = "PARENT_ID")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "dtvSeq")
@SequenceGenerator(name = "dtvSeq", sequenceName = "PARENT_ID_SEQ")
private Long parentId;
@OneToMany(mappedBy = "childEntityPk.parentId", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
Collection<ChildEntity> childrenEntities;
//getters and setters ommited
}
And the children entity, with a composed primary key, partly referencing Parent_id (fk):
@Entity
@Table(name = "CHILDREN")
public class ChildEntity {
@EmbeddedId
private ChildEntityPk childEntityPk;
//other fields
//getter and setters ommited
@Embeddable
private class ChildEntityPk implements Serializable{
long parentId;
String name;
}
}
It works perfectly to fetch data. However, if I want to persist a ParentEntity and its children entities in one go, I get an exception from Oracle.
This exception is thrown because hibernate did not update childEntity.childEntityPk.parentId and is trying to insert null.
I also played with @JoinColumn but without success.
I don't want to have a bi-directional mapping.
Do you have addChild() method or just update the collection? I suggest
public void addChild(ChildEntity child) {
child.setChildEntityPk(this.parentId, "name");
childrenEntities.add(child);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.