使用带有generics的hibernate

我在理解Hibernate如何处理generics方面遇到了一些麻烦,并且想知道实现目标的最佳方法。

给出一个简单的通用实体:

@Entity public class Box{ private T t; @Id private long id; public void setT(T t) { this.t = t; } public T getT() { return t; } public void setId(long id) { this.id = id; } public long getId() { return id; } } 

在进行hibernate初始化时,我得到了exception: ...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 ...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

我几乎可以肯定这是因为我没有给hibernate一个限制实际上是什么的列表。 我知道你可以在注释中指定t之上的诸如targetEntity=String.class东西,但是你失去了使用generics的灵活性。 我可以使用注释限制可接受的generics的范围吗? 例如:如果我想要inheritance自抽象类ParentChildAChildA ,那么该怎么ChildB 。 此外,它还应该能够接受StringHibernate可以处理这样的事情吗?

您正在寻找的可能是Hibernate的隐式多态性 。 还有一个鲜为人知的“任何”关系 ,提供了完全的灵活性,但它有其权衡。 您还可以在多对多中使用“any”。

编辑:我在Github上创建了一个基于你的“Box”类并使用@Any映射的可运行示例。 您可以浏览它 (或专门的Box类 )或检查它并运行它

 git clone git://github.com/zzantozz/testbed tmp cd tmp mvn -q compile exec:java -Dexec.mainClass=rds.hibernate.AnyMapping -pl hibernate-any 

我已经完成了但是使用了子类。

您的generics类必须是抽象的,子类必须定义generics参数