java 将休眠与泛型结合使用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7000428/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using hibernate with generics
提问by Ryan
I am having some trouble understanding how Hibernate deals with generics and was wondering the best way to accomplish my goal.
我在理解 Hibernate 如何处理泛型时遇到了一些麻烦,并且想知道实现我的目标的最佳方法。
Given a simple generic entity:
给定一个简单的通用实体:
@Entity
public class Box<T>{
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;
}
}
When going through hibernate initialization, I am getting the 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
I am nearly certain this is because I haven't given hibernate a list of restrictions of what <T>
can actually be. I know you can specify things such as targetEntity=String.class
above t
in an annotation, but then you lose the flexibility of having generics. Can I limit the scope of what is an acceptable generic using annotations? For instance: What if I want classes ChildA
, ChildB
, whom inherit from an abstract class Parent
to be persistable there. In addition, it should also be able to accept String
s. Can Hibernate
deal with such a thing?
我几乎可以肯定这是因为我没有给 hibernate 列出<T>
实际可能存在的限制。我知道您可以在注释中指定诸如targetEntity=String.class
上面t
的内容,但是这样您就失去了拥有泛型的灵活性。我可以使用注释来限制可接受的泛型的范围吗?例如:如果我希望从抽象类继承的classes ChildA
,可以在那里持久化ChildB
,该怎么办Parent
。此外,它还应该能够接受String
s。能Hibernate
应付这种事吗?
采纳答案by Ryan Stewart
What you're looking for is probably Hibernate's implicit polymorphism. There's also a little-known "any" relationshipwhich gives complete flexibility, but it has its tradeoffs. You can also use an "any" in a many-to-any.
您正在寻找的可能是 Hibernate 的隐式多态性。还有一个鲜为人知的“任何”关系,它提供了完全的灵活性,但它有其权衡。您还可以在多对任何中使用“任何” 。
Edit:I've created a runnable example on Github based around your "Box" class and using an @Any
mapping. You can browse it(or the Box classspecifically) or check it out and run it with
编辑:我基于您的“Box”类并使用@Any
映射在 Github 上创建了一个可运行的示例。您可以浏览它(或专门的Box 类)或检查它并运行它
git clone git://github.com/zzantozz/testbed tmp
cd tmp
mvn -q compile exec:java -Dexec.mainClass=rds.hibernate.AnyMapping -pl hibernate-any
回答by Jerome Cance
I've already done that but with subclasses.
我已经这样做了,但是有子类。
Your generic class must be abstract and subclasses must define the generic parameter
你的泛型类必须是抽象的,子类必须定义泛型参数