如何用泛型类型注释hibernate集合?

时间:2015-05-05 22:26:43

标签: java hibernate jpa hibernate-mapping generics

我有一个类型为List< GenericType < T > >的一对多类成员。在Hibernate中注释这个成员的推荐方法是什么?

病态细节:

@Entity
public class DvOrdered extends DataValue
{
    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinTable(name="dv_ordered_other_reference_ranges", 
        joinColumns = @JoinColumn(name = "reference_range_id"),
        inverseJoinColumns = @JoinColumn(name = "dv_ordered_id"))
    private List<ReferenceRange<T>> otherReferenceRanges;
}

我得到了

Caused by: org.hibernate.AnnotationException: Property com.safehis.ehr.rm.datatypes.quantity.DvOrdered.otherReferenceRanges has an unbound type and no explicit target entity. Resolve this Generic usage issue or set an explicit target attribute (eg @OneToMany(target=) or use an explicit @Type
at org.hibernate.cfg.PropertyContainer.assertTypesAreResolvable(PropertyContainer.java:140)
at org.hibernate.cfg.PropertyContainer.getProperties(PropertyContainer.java:118)
at org.hibernate.cfg.AnnotationBinder.addElementsOfClass(AnnotationBinder.java:1554)
at org.hibernate.cfg.InheritanceState.getElementsToProcess(InheritanceState.java:236)
at org.hibernate.cfg.AnnotationBinder.bindClass(AnnotationBinder.java:775)
at org.hibernate.cfg.Configuration$MetadataSourceQueue.processAnnotatedClassesQueue(Configuration.java:3845)
at org.hibernate.cfg.Configuration$MetadataSourceQueue.processMetadata(Configuration.java:3799)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1412)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1846)

提前感谢您的回复。

1 个答案:

答案 0 :(得分:1)

通用信息在编译时丢失,因为类型擦除,因此Hibernate无法确定您的案例中T的类型。

您可以将代码更改为:

private List<ReferenceRange<T>> otherReferenceRanges;

然后使用继承,以便每个ReferenceRange子类嵌入某种类型。

public abstract class ReferenceRange<T> {

    public abstract T getReference();
}

public class IntegerReferenceRange extends ReferenceRange<Integer> {

    private Integer reference;

    @Override
    public Integer getReference() {
        return reference;
    }
}