I’ve been working on an Entity, oneToMany relationship, the problem is that whenever I use this:
//Parent class
@OneToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE}, fetch = FetchType.EAGER,
targetEntity = FeedbackCategory.class, mappedBy = "parent")
@PrivateOwned
@OrderBy("category ASC")
private List<Child> children;
//... other code here, i.e. getters-setters
@PrePersist
@PreUpdate
void prePersistUpdate() {
// set the foreign key of child to this.ID
if(children != null && !children.isEmpty())
{
for(Child ch: children)
{
ch.setParent(this);
}
}
}
when updating the Parent.class, especially when clean updating the entity, the Id of Parent weren’t being persisted together with the child entity(as foreign key). help please…
it seems that @PreUpdate is not working, @PrePersist totally works.
In general it would be better to correctly maintain your model.
Add an addChild() method that adds the child and sets the parent. Then you model will not be corrupt.
@PreUpdate occurs later in the commit process (after it has determined it needs to update the object). I don’t think there is an earlier JPA event, but you can use the EclipseLink PreWrite event. You will need to use a DescriptorEventListener for this, which can be configured the same way an an EntityListener.