java - 使用 Hibernate 持久化接口(interface)集合

标签 java hibernate interface

我想用 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]

我知道 @OneToManytargetEntity 属性,但这意味着只有狗或猫可以住在我的动物园里。

有没有办法用 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/

相关文章:

java - 如何使程序考虑数组列表中不存在的索引

typescript - 定义接口(interface) : object with unknown number and name of properties

c# - 如何创建返回实现接口(interface)的类的类型的方法的通用接口(interface)?

java - 简单查询 : not implemented by SQLite JDBC driver

java - 有没有办法在没有 DTO 的情况下将 Hibernate 实体公开为 RESTful 资源?

java - Mavericks 上的 Eclipse 错误 : posix_spawn is not a supported process launch mechanism on this platform

hibernate - 将父类(super class)和子类映射到 Hibernate 中的不同表

java - 如何从 Hibernate 运行 SEQUENCE setVal

java - org.hibernate.exception.SQLGrammarException : could not get next sequence value

Java - 理解接口(interface)