我有简单的枚举:
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;
}
}
现在,当我尝试使用填充元素保存实体时 - 一切都很好 - 实体被保存而没有问题。当我尝试从数据库中获取实体时,hibernate 决定他不喜欢我的集合,然后将其删除。来自日志的 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 时它可以工作 - 但它不应该也适用于懒惰吗?
我正在使用休眠 4.2.0.Final、SpringData、PostreSQL 和 hibernate.enable_lazy_load_no_trans