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;
}
}
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
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?
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.
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 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
I've already done that but with subclasses.
Your generic class must be abstract and subclasses must define the generic parameter
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With