I have a OneToMany mapping and if the user loads the "one" and then gets an instance of one of the "many" items contained by the "one", then persists either object, clears caches, reloads the "one" item and finally they alter the detached "many" instance, Hibernate does not complain nor does the alteration get persisted.
OK, that was a crazy verbal explanation, here's the code:
Code:
Container container = loadContainer(); // using HQL, retrieves the object
Contained contained = container.getContained(someIdentifer);
_em.persist(container);
_em.getTransaction().commit();
_em.clear();
Container container2 = loadContainer(); // same as above
contained.changeSomething();
_em.persist(container2);
_em.getTransaction().commit(); // hibernate does not throw detached object exception
_em.clear();
Container container = loadContainer(); // same as above
assertEquals(contained, container3.getContained(someIdentifier)); // this assertion fails because of the detachment, user expects them to be equal
Here's the mapping within Container:
Code:
@OneToMany(targetEntity = com.xxx.Contained.class, mappedBy = "container", cascade = {CascadeType.REMOVE,
CascadeType.PERSIST })
@org.hibernate.annotations.Cascade(value = org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
public Set<Contained> getContained() {
return _containedItems;
}
Here's the mapping within Contained:
Code:
@ManyToOne(targetEntity = com.xxx.Container.class, cascade = CascadeType.PERSIST)
@JoinColumn(name = "containerid")
public Container getContainer() {
return _container();
}
How do you handle this situation as an API developer? I want to prevent my users from altering detached objects but in this situation, they can persist without exception.
Thanks!
(this is with Hibernate 3.3.1 and Annotations 3.4)