I have a situation best described like this:
Code:
class Car {
@OneToMany(cascade = { CascadeType.ALL })
List<Part> parts;
}
Code:
class Part {
@OneToMany(cascade = { CascadeType.ALL })
List<Part> subparts;
@ManyToOne(nullable=false)
Car car;
@ManyToOne
Part parent;
}
I am then trying to add a subpart, that is a part with a non-null parent and a non-null car. All persistent operations are in stateful session EJBs with extended persistence context and REQURES_NEW transaction settings.
I have tried these strategies with the following outcomes:
Strategy I (how it should work): Code:
subpart = em.persist(subpart);
subpart.getParent().getSubparts().add(subpart);
subpart.getCar().getParts.add(subpart);
...
em.query("from Part where car = :car ").setParameter("car", someCar);
The outcome is that a subsequent query for parts will give an Exception when the session flush is triggered (why is it triggered in the first place). "PersistentObjectException: detached entity passed to persist: foo.bar.Part" is the message.
Strategy II:Code:
parent().getSubparts().add(subpart);
car().getParts.add(subpart);
em.merge(parent);
The outcome is that a subsequent query for parts will again trigger a flush which will also merge the car. Then two identical subparts are created in the database.
Strategy III:Code:
em.persist(subpart);
em.query("from Part where car = :car ").setParameter("car", someCar);
The outcome is that the newly added part is not visible as a subpart in the parent. Quite logical since it was never added there in the first place.
If anybody has an idea, I would be grateful.
Code: