Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using hibernate with generics

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 Strings. Can Hibernate deal with such a thing?

like image 351
Ryan Avatar asked Aug 09 '11 17:08

Ryan


2 Answers

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
like image 51
Ryan Stewart Avatar answered Sep 29 '22 08:09

Ryan Stewart


I've already done that but with subclasses.

Your generic class must be abstract and subclasses must define the generic parameter

like image 41
Jerome Cance Avatar answered Sep 29 '22 06:09

Jerome Cance