Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/hibernate/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Hibernate JPA2中分离对象的问题_Hibernate_Spring_Jpa_Persistence_Jpa 2.0 - Fatal编程技术网

Hibernate JPA2中分离对象的问题

Hibernate JPA2中分离对象的问题,hibernate,spring,jpa,persistence,jpa-2.0,Hibernate,Spring,Jpa,Persistence,Jpa 2.0,我正在使用JPA2和Hibernate实现。我正在尝试持久化一个用户对象,它有一个权限列表 @OneToMany(mappedBy = "user", fetch = LAZY, cascade = ALL) private List<UserAuthority> userAuthorities; 谢谢 Dawid当您传递某个分离的实体以进行持久化时,通常会发生这种情况 userAuthority.setAuthority(authorityDao.getByName(Author

我正在使用JPA2和Hibernate实现。我正在尝试持久化一个用户对象,它有一个权限列表

@OneToMany(mappedBy = "user", fetch = LAZY, cascade = ALL)
private List<UserAuthority> userAuthorities;
谢谢


Dawid

当您传递某个分离的实体以进行持久化时,通常会发生这种情况

userAuthority.setAuthority(authorityDao.getByName(Authorities.ROLE_USER
                .toString()));

此代码实际上加载持久化实体并设置为新的
userAuthority
,而不是在
userAuthority

中分配新的Authority对象或重新访问
Authority
的级联映射部分,这是使用事务性dao方法(使用spring)产生的众多复杂问题之一

通常的做法是使用
@Transactional
注释您的服务方法

在您的情况下,您的
权限
对象似乎是从不同的会话中获得的,因此当您调用
persist()
时,它会被分离。因此:

  • 去掉DAO方法上的
    @Transactional
    ,而将其放在服务方法上
  • 尝试一下
    merge(…)
    (而不是
    persist()

今天晚些时候我会试试,看看会发生什么
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
userAuthority.setAuthority(authorityDao.getByName(Authorities.ROLE_USER
                .toString()));