Hibernate 是否有可能执行以下实体结构?
@Entity
public class Person {
@OneToMany
private Map<Class<? extends PersonRole>, PersonRole> personRoles;
public <T extends PersonRole> T getRole(Class<T> roleClass) {
return roleClass.cast(roles.get(roleClass));
}
}
@Entity
public abstract class PersonRole {
@ManyToOne
private Person person;
}
基本上 Hibernate 可以持久化这个映射的实体,但是不能再从数据库中加载它,但有以下例外:
Exception in thread "main" org.hibernate.HibernateException: null index column for collection: de.his.cs.sys.hibernate.Person.roles
at org.hibernate.persister.collection.AbstractCollectionPersister.readIndex(AbstractCollectionPersister.java:822)
at org.hibernate.collection.internal.PersistentMap.readFrom(PersistentMap.java:277)
at org.hibernate.loader.Loader.readCollectionElement(Loader.java:1189)
at org.hibernate.loader.Loader.readCollectionElements(Loader.java:804)
at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:655)
at org.hibernate.loader.Loader.doQuery(Loader.java:854)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:293)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:263)
at org.hibernate.loader.Loader.loadCollection(Loader.java:2094)
at org.hibernate.loader.collection.CollectionLoader.initialize(CollectionLoader.java:61)
一种解决方法可能是使用“简单”集合并用拦截器填充地图,但我希望有可能在没有额外基础设施的情况下实现这一点。