I have an entity Property
which has several PropertyAttributes
- managed as list, i.e.
@OneToMany(mappedBy = "property", cascade = { CascadeType.ALL}, fetch = FetchType.EAGER)
@JoinFetch(value = JoinFetchType.INNER)
private List<PropertyAttribute> propertyAttribute;
in the PropertyAttribute
I have as well a reference to the Property
, i.e.
@Id
@JsonIgnore
@JoinColumn(name = "property_id")
@ManyToOne
private Property property;
when I save a new Property
,e.g. id=10400
than the additional PropertyAttribute
is saved as well with the same id - as expected. My save()
method looks like:
public void save(){
//begin transaction
getEntityManager.persist(newProperty);
// end transaction...
//begin transaction...
getEntityManager.merge(newPropertyAttriubtes);
// end transaction
}
But when I perform the second round of save()
(now with id=10401
then I get strange results, namely:
getEntityManager().find(Property.class,10400)
has now PropertyAttribute
with Property
- id
= 10401, i.e. from the last saved record (=wrong content!)
Any ideas why it fails with the second save? Might it be a DB-issue? Or EclipseLink?
I finally figured out how to do it properly :-/ Just in case others struggle the same...
public void save(){
//begin transaction
getEntityManager.persist(newProperty);
// end transaction...
newPropertyAttriubtes.forEach(attr -> {
//begin transaction...
getEntityManager.merge(attr);
// end transaction
newProperty.attach(attr)
}
//begin transaction
// to have the PropertyAttributes attached in the EntityManager => merge
getEntityManager.merge(newProperty);
// end transaction...
}
}
Thx for Chris to point me to the correct direction to not change the Entity after JPA manage it!