Hi,
I have a question about the difference between org.hibernate.annotations.CascadeType.SAVE_UPDATE and javax.persistence.CascadeType.PERSIST. I've understood from messages on this forum that session.persist(obj) is more or less the same thing as session.saveOrUpdate(obj), however, they seem to differ in one extremely important detail:
I've set up a class Person that has a property of class PersonType with a ManyToOne mapping (using @ManyToOne), the idea being that more than one person can be of a particular type. In a test, I tried to instantiate several of these classes like so:
Code:
PersonType type = new PersonType("Member");
Person person1 = new Person("Bill", "Joy", "billa@joy.com", type);
Person person2 = new Person("Bill", "Joy", "billb@joy.com", type);
Person person3 = new Person("Bill", "Joy", "billc@joy.com", type);
dao.savePerson(person1);
dao.savePerson(person2);
dao.savePerson(person3);
The important part is that the same PersonType object is used on all the objects. When I use the following code in conjunction with session.saveOrUpdate(obj) everything works.
Code:
@ManyToOne
@Cascade(CascadeType.SAVE_UPDATE)
@JoinColumn(name = "type_fk", nullable = false)
public PersonType getType() {
return personType;
}
However, when I use the following code in conjunction with session.persist(obj) I get a
PersistenObjectException: detached entity passed to persistCode:
@ManyToOne(cascade = CascadeType.PERSIST)
@JoinColumn(name = "type_fk", nullable = false)
public PersonType getType() {
return personType;
}
The detached object is the PersonType object in Person, which is detached from the session after I saved it the first time, and then cannot be used for the second save operation.
What my question comes down to is this: why does the persist method, under similar cascading circumstances, fail to reattache the object automatically whereas the saveOrUpdate does achieve this? For objects without dependent persisted objects persist() seems to work like saveOrUpdate(), but this seems like a pretty big (and inconvenient difference). Is there any way to achieve the saveOrUpdate() functionality with just EJB3 annotations?
I'm using hibernate version 3.2.0.CR2 and annotations version 3.2.0.CR1.
Regards,
Maarten