use*_*008 5 java hibernate hibernate-mapping
我正在寻找一种Type在实体管理器配置阶段绑定特定实体字段的方法。我需要它能够使用外部源将额外的“规则”应用于目标实体字段,而无需更改实体类。
因此,基本上我正在尝试避免如下硬编码@Type注释方式:
@Type(type = foo.package.MyType, parameters = {
@Parameter(name = "fooProperty", value = "fooValue")
})
private String someField;
Run Code Online (Sandbox Code Playgroud)
相反,我想在以someField编程方式构建模型时将Type设置为。
这是我以前见过的一种方法。它有点低级,所以我怀疑有一种更干净的方法可以做到这一点。
这使用 Hibernate 中的自定义来允许我们在创建( )Persister时替换类型。SessionFactoryEntityManagerFactory
首先,@Persister使用注解来声明自定义Persister:
@Entity
@Persister(impl = MyPersister.class)
public class EntityWithPersister {
private String someField;
Run Code Online (Sandbox Code Playgroud)
那么通常自定义持久化器应该SingleTableEntityPersister在 Hibernate 中扩展。如果实体使用不同的@Inheritance(strategy),则可能需要扩展JoinedSubclassEntityPersister或UnionSubclassEntityPersister替代。
这提供了在构建时更改类型的机会,例如:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
如果您需要访问更多您所在的上下文,creationContext.getSessionFactory()这可能是一个很好的起点。