Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
475 views
in Technique[技术] by (71.8m points)

java - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...