这是我以前见过的一种方式。它有点低级,所以我怀疑有一种更清洁的方法可以做到这一点。
这使用 Hibernate 中的自定义 Persister 来允许我们在创建 SessionFactory ( EntityManagerFactory ) 时替换类型。
首先,@Persister注解用于声明自定义Persister:
@Entity
@Persister(impl = MyPersister.class)
public class EntityWithPersister {
private String someField;
那么通常自定义持久化器应该在 Hibernate 中扩展 SingleTableEntityPersister。如果实体使用不同的@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;
}
}
如果您需要访问您所处的更多上下文,creationContext.getSessionFactory() 可能是一个很好的起点。