如何以编程方式为选定的实体字段绑定 Hibernate 类型?

How to programmatically bind Hibernate Type for selected entity fields?

我正在寻找一种在实体管理器配置阶段为特定实体字段绑定 Type 的方法。我需要它能够使用外部源将额外的 "rules" 应用到目标实体字段而无需实体 class 更改。

所以基本上我试图避免硬编码 @Type 注释方式如下:

@Type(type = foo.package.MyType, parameters = {
    @Parameter(name = "fooProperty", value = "fooValue")
})
private String someField;

相反,我想在以编程方式构建模型时为 someField 设置类型。

这是我以前见过的一种方式。它有点低级,所以我怀疑有更简洁的方法来做到这一点。

这在 Hibernate 中使用自定义 Persister 以允许我们在创建 SessionFactory ( EntityManagerFactory ) 时替换类型。

首先使用@Persister注解声明自定义Persister:

@Entity
@Persister(impl = MyPersister.class)
public class EntityWithPersister {

    private String someField;

然后通常自定义持久化程序应该在 Hibernate 中扩展 SingleTableEntityPersister。如果实体使用不同的 @Inheritance(strategy),则可能需要扩展 JoinedSubclassEntityPersisterUnionSubclassEntityPersister

这提供了在构造点更改类型的机会,例如:

public class MyPersister extends SingleTableEntityPersister {

    public MyPersister(PersistentClass persistentClass,
            EntityDataAccess cacheAccessStrategy,
            NaturalIdDataAccess naturalIdRegionAccessStrategy,
            PersisterCreationContext creationContext)
            throws HibernateException {
        super(modify(persistentClass), cacheAccessStrategy,
                naturalIdRegionAccessStrategy, creationContext);
    }

    private static PersistentClass modify(PersistentClass persistentClass) {
        SimpleValue value = (SimpleValue) persistentClass
                .getProperty("someField").getValue();
        value.setTypeName(MyType.class.getName());
        return persistentClass;
    }
}

如果您需要访问更多您所在的上下文,creationContext.getSessionFactory() 可能是一个很好的起点。