[英]Persist collection of interface using Hibernate
I want to persist my litte zoo with Hibernate: 我想用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
}
When I try to persist the zoo, Hibernate complains: 当我试图坚持动物园时,Hibernate抱怨道:
Use of @OneToMany or @ManyToMany targeting an unmapped class: blubb.Zoo.animals[blubb.Animal]
I know about the targetEntity
-property of @OneToMany
but that would mean, only Dogs OR Cats can live in my zoo. 我知道
@OneToMany
的targetEntity
-property但这意味着,只有Dogs或Cats可以住在我的动物园里。
Is there any way to persist a collection of an interface, which has several implementations, with Hibernate? 有没有办法用Hibernate来持久化一个具有多个实现的接口集合?
JPA annotations are not supported on interfaces. 接口不支持JPA注释。 From Java Persistence with Hibernate (p.210):
从Java Persistence with Hibernate (p.210):
Note that the JPA specification doesn't support any mapping annotation on an interface!
请注意,JPA规范不支持接口上的任何映射注释! This will be resolved in a future version of the specification;
这将在规范的未来版本中得到解决; when you read this book, it will probably be possible with Hibernate Annotations.
当您阅读本书时,可能会使用Hibernate Annotations。
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). 一种可能的解决方案是使用带有
TABLE_PER_CLASS
继承策略的抽象实体(因为您不能在关联中使用映射的超类 - 它不是实体)。 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>();
...
}
But there is not much advantages in keeping the interface IMO (and actually, I think persistent classes should be concrete). 但是保持接口IMO没有太大的优势(实际上,我认为持久化类应该是具体的)。
I can guess that what you want is mapping of inheritance tree. 我猜你想要的是继承树的映射。 @Inheritance annotation is the way to go.
@Inheritance注释是要走的路。 I don't know if it will work with interfaces, but it will definitely work with abstract classes.
我不知道它是否适用于接口,但它肯定适用于抽象类。
我认为你必须使用@Entity
来注释接口,我们必须在所有getter和setter接口上注释@Transient
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.