将休眠与泛型结合使用 [英] Using hibernate with generics
问题描述
我在理解 Hibernate 如何处理泛型时遇到了一些麻烦,并且想知道实现我的目标的最佳方法.
I am having some trouble understanding how Hibernate deals with generics and was wondering the best way to accomplish my goal.
给定一个简单的通用实体:
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;
}
}
在进行休眠初始化时,我收到异常:...有一个未绑定的类型并且没有明确的目标实体.解决此通用使用问题或设置显式目标属性(例如 @OneToMany(target=) 或使用显式 @Type
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
我几乎可以肯定这是因为我没有给 hibernate 列出 <T>
实际上可以是什么的限制.我知道你可以在注释中指定诸如 targetEntity=String.class
上面的 t
之类的东西,但是你失去了拥有泛型的灵活性.我可以使用注释来限制可接受的泛型的范围吗?例如:如果我希望从抽象类 Parent
继承的类 ChildA
、ChildB
可以在那里持久化,该怎么办?此外,它还应该能够接受String
s.Hibernate
可以处理这样的事情吗?
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 的 隐式多态.还有一个 小-已知的任何"关系提供了完全的灵活性,但它有其权衡.您还可以在 多对多.
What you're looking for is probably Hibernate's implicit polymorphism. There's also a little-known "any" relationship which gives complete flexibility, but it has its tradeoffs. You can also use an "any" in a many-to-any.
我在 Github 上创建了一个基于Box"类并使用 @Any
映射的可运行示例.您可以浏览它(或Box class 特别)或检查出来并运行它
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 class specifically) or check it out and run it with
git clone git://github.com/zzantozz/testbed tmp
cd tmp
mvn -q compile exec:java -Dexec.mainClass=rds.hibernate.AnyMapping -pl hibernate-any
这篇关于将休眠与泛型结合使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!