开发者

Problem with Detached object in JPA2

开发者 https://www.devze.com 2023-02-21 23:20 出处:网络
I\'m using JPA2 and Hibernate implementation. I\'m trying to persist a User object, which got a List of Authorities

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 of persist())


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号