在泛型中使用hibernate

在泛型中使用hibernate

本文介绍了在泛型中使用hibernate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



给定一个简单的通用实体:



  @Entity 
public class Box< T> {

private T t;
@Id
私人长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;


在进行hibernate初始化时,我收到异常: ...有一个未绑定的类型,没有明确的目标实体。解决这个泛型用法问题或者设置一个明确的目标属性(例如@OneToMany(target =)或者使用一个明确的@Type



确定这是因为我没有给hibernate一个限制< T> 实际上的限制列表。我知道你可以指定诸如 targetEntity = String.class 在注释中超过 t ,但是您失去了泛型的灵活性。我可以限制什么是范围例如:如果我想要从抽象类继承的类 ChildA ChildB ,该怎么办? 在这里是可持久化的,另外它还应该能够接受 String s。Can <$ c $ H> 处理这样的事情

。还有一个,它提供了完全的灵活性,但它有其折衷。您也可以在。



编辑:我在Github上创建了一个基于Box类并使用 @Any 映射。您可以(或)或者检查并运行它

$ g $ git clone git: b mvn -q compile exec:java -Dexec.mainClass = rds.hibernate.AnyMapping -pl hibernate-any


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?

解决方案

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

这篇关于在泛型中使用hibernate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 04:43