Hibernate 6.2中已弃用@Persister的替代方案咨询
Hibernate 6.2中替代@Persister实现删除Agency不删除AGENCY_TYPE_ROLE关联行的方案
背景与数据库表结构
我拥有Agency和Role两个实体,机构被划分为不同类型,每种机构类型与一组Role的关联存储在AGENCY_TYPE_ROLE表中,表结构如下:
AGENCY_TYPE_ROLE table: AGENCY_TYPE_ID integer not null, ROLE_ID integer not null, (AGENCY_TYPE_ID, ROLE_ID) primary key,
核心需求
删除Agency实体时,对应机构类型在AGENCY_TYPE_ROLE表中的关联行不得被删除。
Hibernate 6.2.0之前的实现方式
此前我通过@Persister注解搭配自定义ReadOnlyCollectionPersister类实现该需求:
Agency实体代码
@Table(name = "AGENCY", schema = "TEST") public class Agency { private Set<Role> roles; @ManyToMany @JoinTable( name = "AGENCY_TYPE_ROLE", schema = "TEST", joinColumns = @JoinColumn(name = "AGENCY_TYPE_ID"), inverseJoinColumns = @JoinColumn(name = "ROLE_ID")) @Persister(impl= ReadOnlyCollectionPersister.class) public Set<Role> getRoles() { return (roles == null ? null : roles); } public void setRoles(Set<Role> roles) { this.roles = roles; } }
自定义ReadOnlyCollectionPersister类
public class ReadOnlyCollectionPersister extends BasicCollectionPersister { private static Collection asInverse(Collection collection) { collection.setInverse(true); return collection; } public ReadOnlyCollectionPersister( Collection collectionBinding, CollectionDataAccess cacheAccessStrategy, RuntimeModelCreationContext creationContext) throws MappingException, CacheException { super(asInverse(collectionBinding), cacheAccessStrategy, creationContext); } }
Hibernate 6.2中的问题
Hibernate 6.2已正式弃用@Persister注解,官方文档说明如下:
2.4.10. Define a custom entity persister
Supplying a custom persister has been allowed historically, but has never been fully supported. Hibernate 6 provides better, alternative ways to accomplish the use cases for a custom persister. As of 6.2 @Persister has been formally deprecated.
我尝试了多种方法,但尚未找到不使用@Persister的替代方案,恳请提供可行的见解或实现建议。
内容的提问来源于stack exchange,提问作者Puhong
相关产品推荐
相关产品推荐

