Hibernate persistence by reachability & detached objects
I'm curious to know how Hibernate would handle the following situation.
Let's say we have a User
entity, which has a country
propert开发者_如何学Cy, set to cascade the persistence:
public class User {
@ManyToOne(cascade=CascadeType.PERSIST)
protected Country country;
// ...
}
Now, what if we assign a detached Country
object to the User
...
user.setCountry(someDetachedCountry);
... but a Country
with the same identity already exists in the current session?
Will the commit fail with an exception, or will it just use the detached country's identity as if it was in the session? In the latter case, will Hibernate try to cascade persistence to the detached Country
's properties, if any of them are set to cascade?
This is not an uncommon problem, especially when people try to use primitive types as identifiers and initialize them to values like -1. You're going to see a message similar to the following:
javax.persistence.PersistenceException:
org.hibernate.PersistentObjectException: detached entity passed to persist: Country
精彩评论