hibernate enum @elementcollection 初始化后删除

2024-04-16

我有简单的枚举:

public enum Privilege implements Serializable {        
   P1,
   P2,
   P3;
}

它被映射到这样的实体中:

@Entity
@Table(name = "rol_roles",
    uniqueConstraints = {...)
public class Role extends AbstractSomething {

 ...

    @ElementCollection(targetClass = Privilege.class, fetch = FetchType.LAZY) 
    @CollectionTable(name = "rol_roles_privileges", 
        joinColumns =
        @JoinColumn(name = "role_id"))
    @Column(name = "privilege", nullable = false)
    @Enumerated(EnumType.STRING)
    private Set<Privilege> privileges = EnumSet.noneOf(Privilege.class);

    public Set<Privilege> getPrivileges() {
        return privileges;
    }

    public void setPrivileges(Set<Privilege> privileges) {
        this.privileges = privileges;
    }
}

现在,当我尝试保存带有填充元素的实体时 - 一切都很好 - 实体可以毫无问题地保存。当我尝试从数据库获取实体时,休眠状态决定他不喜欢我的集合,并将其删除。日志中的sql:

Hibernate: 
    select
        role0_.id as id1_6_,
        role0_.version_num as version2_6_,
        role0_.code as code3_6_,
        role0_.comments as comments4_6_,
        role0_.title as title5_6_,
        role0_.title_en as title6_6_,
        role0_.valid_from as valid7_6_,
        role0_.valid_till as valid8_6_ 
    from
        rol_roles role0_ 
    where
        role0_.id=? 
 Hibernate: 
    select
        privileges0_.role_id as role1_6_0_,
        privileges0_.privilege as privileg2_7_0_,
    from
        rol_roles_privileges privileges0_ 
    where
        privileges0_.role_id=? 
 Hibernate: 
    delete 
    from
        rol_roles_privileges 
    where
        role_id=?

由于集合是惰性的,因此特权和删除语句会继续进行集合初始化。我尝试按照类似线程中的建议添加 @OrderColumn 注释,但这没有帮助。 与类似情况一样,没有插入语句,因此读取对象只是刷出集合。 表是这样创建的:

create table rol_roles_privileges (
        role_id int8 not null,
        privilege varchar(255) not null,
        primary key (role_id, privilege)
    );

奇怪的是(或者可能不是),当我设置 fetchtype.EAGER 时它会起作用 - 但它不应该也适用于懒惰吗?

我正在使用 hibernate 4.2.0.Final、Spring Data、PostgreSQL 和 hibernate.enable_lazy_load_no_trans


对于未来的谷歌用户: 使用enable_lazy_load_no_trans时,hibernate 4.2似乎有问题。 这个错误可能与https://hibernate.atlassian.net/browse/HHH-7524 https://hibernate.atlassian.net/browse/HHH-7524

它正在记录: 日志: ERROR AssertionFailure:43 - HHH000099:发生断言失败(这可能表明 Hibernate 中存在错误,但更可能是由于会话的不安全使用):org.hibernate.AssertionFailure:集合所有者与会话不关联:org.hibernate。测试.ondemandload.Store.inventories WARN AbstractPersistentCollection:246 - 无法关闭用于加载与无会话关联的惰性集合的临时会话

我现在使用 hibernate 4.1.7,并且所有延迟加载都可以正常工作。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

hibernate enum @elementcollection 初始化后删除 的相关文章

随机推荐