我想让我的小动物园坚持使用Hibernate:
@Entity
@Table(name = "zoo")
public class Zoo {
@OneToMany
private Set<Animal> animals = new HashSet<Animal>();
}
// Just a marker interface
public interface Animal {
}
@Entity
@Table(name = "dog")
public class Dog implements Animal {
// ID and other properties
}
@Entity
@Table(name = "cat")
public class Cat implements Animal {
// ID and other properties
}当我试图持久化动物园时,Hibernate抱怨道:
Use of @OneToMany or @ManyToMany targeting an unmapped class: blubb.Zoo.animals[blubb.Animal]我知道@OneToMany的targetEntity-property,但这意味着只有狗或猫才能住在我的动物园里。
有没有办法用Hibernate持久化一个有多个实现的接口集合?
发布于 2010-05-27 12:28:23
JPA注释在接口上不受支持。来自Java Persistence with Hibernate (第210页):
注意,JPA规范不支持接口上的任何映射注释!这个问题将在该规范的未来版本中得到解决;当您阅读本书时,可能会使用Hibernate注解。
一种可能的解决方案是使用具有TABLE_PER_CLASS继承策略的抽象实体(因为您不能在关联中使用映射的超类-它不是实体)。如下所示:
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class AbstractAnimal {
@Id @GeneratedValue(strategy = GenerationType.TABLE)
private Long id;
...
}
@Entity
public class Lion extends AbstractAnimal implements Animal {
...
}
@Entity
public class Tiger extends AbstractAnimal implements Animal {
...
}
@Entity
public class Zoo {
@Id @GeneratedValue
private Long id;
@OneToMany(targetEntity = AbstractAnimal.class)
private Set<Animal> animals = new HashSet<Animal>();
...
}但是保持接口IMO并没有太多的好处(实际上,我认为持久化类应该是具体的)。
参考文献
发布于 2010-05-26 20:50:51
我可以猜到你想要的是继承树的映射。@继承注解是一种可行的方法。我不知道它是否适用于接口,但它肯定适用于抽象类。
发布于 2010-06-06 02:28:02
我认为你也必须用@Entity注释接口,我们必须在接口的所有getters和setters上注释@Transient。
https://stackoverflow.com/questions/2912988
复制相似问题