使用 Hibernate 持久化接口集合 [英] Persist collection of interface using Hibernate
问题描述
我想用 Hibernate 保留我的小动物园:
I want to persist my litte zoo with 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 抱怨:
When I try to persist the zoo, Hibernate complains:
Use of @OneToMany or @ManyToMany targeting an unmapped class: blubb.Zoo.animals[blubb.Animal]
我知道 @OneToMany
的 targetEntity
属性,但这意味着,只有狗或猫可以住在我的动物园里.
I know about the targetEntity
-property of @OneToMany
but that would mean, only Dogs OR Cats can live in my zoo.
有没有办法用 Hibernate 持久化一个接口的集合,它有几个实现?
Is there any way to persist a collection of an interface, which has several implementations, with Hibernate?
推荐答案
接口不支持 JPA 注释.来自 Java Persistence with Hibernate(第 210 页):
JPA annotations are not supported on interfaces. From Java Persistence with Hibernate (p.210):
注意JPA规范不支持任何映射注解在一个界面上!这将得到解决在未来的版本中规格;当你读到这个书,这可能是可能的带有 Hibernate 注释.
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
继承策略的抽象实体(因为您不能在关联中使用映射的超类——它不是实体——).像这样:
A possible solution would be to use an abstract Entity with a TABLE_PER_CLASS
inheritance strategy (because you can't use a mapped superclass - which is not an entity - in associations). Something like this:
@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 并没有太大的优势(实际上,我认为持久类应该是具体的).
But there is not much advantages in keeping the interface IMO (and actually, I think persistent classes should be concrete).
这篇关于使用 Hibernate 持久化接口集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!