Using hibernate with generics

Viewed 19131

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?

2 Answers
Related