Problem with Detached object in JPA2
I'm using JPA2 and Hibernate implementation. I'm trying to persist a User object, which got a List of Authorities
@OneToMany(mappedBy = "user", fetch = LAZY, cascade = ALL)
private List<UserAuthority> userAuthorities;
In my service there is :
UserAuthority userAuthority = new UserAuthority();
userAuthority.setAuthority(authorityDao.getByName(Authorities.ROLE_USER
.toString()));
userAuthority.setUser(user);
List<UserAuthority> authorities = new ArrayList<UserAuthority开发者_开发问答>();
authorities.add(userAuthority);
user.setUserAuthorities(authorities);
userDao.persist(user);
The "getByName"
method in authorityDao
finds a ROLE_USER
in my database. Both userDao and authorityDao got @Transactional annotations. Now when I try to call userDao.persist(user)
I got an exception. Why and how solve it?
org.springframework.orm.jpa.JpaSystemException: org.hibernate.PersistentObjectException: detached entity passed to persist: pl.flamewars.entity.Authority; nested exception is javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist: pl.flamewars.entity.Authority
Thanks
Dawid
That is one of the many complications that arise from using transactional dao methods (with spring).
The usual practice is to have your service methods annotated with @Transactional
.
In your case, your Authority
object appears to be obtained from a different session, and hence it is detached when you call persist()
. So:
- Get rid of
@Transactional
on DAO methods and place it on service methods instead - Give
merge(..)
a try (instead ofpersist()
)
This generally happens when you pass some detached entity to persist..
userAuthority.setAuthority(authorityDao.getByName(Authorities.ROLE_USER
.toString()));
This code actually loads the persisted entity and sets to the new userAuthority
, instead of this assign the new Authority object or revisit the cascade mapping part of Authority
in UserAuthority
精彩评论