簡體   English   中英

使用Hibernate持久收集界面

[英]Persist collection of interface using 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
}

當我試圖堅持動物園時,Hibernate抱怨道:

Use of @OneToMany or @ManyToMany targeting an unmapped class: blubb.Zoo.animals[blubb.Animal]

我知道@OneToManytargetEntity -property但這意味着,只有Dogs或Cats可以住在我的動物園里。

有沒有辦法用Hibernate來持久化一個具有多個實現的接口集合?

接口不支持JPA注釋。 Java Persistence with Hibernate (p.210):

請注意,JPA規范不支持接口上的任何映射注釋! 這將在規范的未來版本中得到解決; 當您閱讀本書時,可能會使用Hibernate Annotations。

一種可能的解決方案是使用帶有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沒有太大的優勢(實際上,我認為持久化類應該是具體的)。

參考

我猜你想要的是繼承樹的映射。 @Inheritance注釋是要走的路。 我不知道它是否適用於接口,但它肯定適用於抽象類。

我認為你必須使用@Entity來注釋接口,我們必須在所有getter和setter接口上注釋@Transient

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM