我想用 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
属性,但这意味着只有狗或猫可以住在我的动物园里。
有没有办法用 Hibernate 持久化一个接口(interface)的集合,它有几个实现?
最佳答案
接口(interface)不支持 JPA 注释。来自 Java Persistence with Hibernate (p.210):
Note that the JPA specification doesn’t support any mapping annotation on an interface! This will be resolved in a future version of the specification; when you read this book, it will probably be possible with Hibernate Annotations.
一种可能的解决方案是使用具有 TABLE_PER_CLASS
继承策略的抽象实体(因为您不能在关联中使用映射的父类(super 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>();
...
}
但保留接口(interface) IMO 并没有太大的优势(实际上,我认为持久类应该是具体的)。
引用文献
关于java - 使用 Hibernate 持久化接口(interface)集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2912988/