Hibernate继承单表

时间:2018-02-22 09:55:38

标签: java hibernate single-table-inheritance

我正在尝试使用DB表“人员”实现单个表Hibernate继承策略。

我有一个家庭,其中包含丈夫,妻子,孩子名单和其他囚犯名单。每个人都可能是许多家庭的成员(即丈夫可能是一个家庭的丈夫,另一个是其他孩子)。

@Entity
@Table(name = "families")
public class Family extends BaseObject {
    private Parent husband;
    private Parent wife;
    private String surname;

    private List<Child> children = new ArrayList<Child>();
    private List<Other> others = new ArrayList<Other>();

    @ManyToOne(optional = true, cascade = CascadeType.ALL)
    @JoinColumn(name = "husband_id", nullable = true)
    public Parent getHusband() {
        return husband;
    }

    @ManyToOne(optional = true, cascade = CascadeType.ALL)
    @JoinColumn(name = "wife_id", nullable = true)
    public Parent getWife() {
        return wife;
    }

    @LazyCollection(LazyCollectionOption.TRUE)
    @ManyToMany(cascade=CascadeType.ALL)
    @JoinTable(name="persons_families", joinColumns=@JoinColumn(name="family_id"), inverseJoinColumns=@JoinColumn(name="person_id"))
    public List<Other> getOthers() {
        return others;
    }

    @LazyCollection(LazyCollectionOption.TRUE)
    @ManyToMany(cascade=CascadeType.ALL)
    @JoinTable(name="persons_families", joinColumns=@JoinColumn(name="family_id"), inverseJoinColumns=@JoinColumn(name="person_id"))
    public List<Child> getChildren() {
        return children;
    }

人是所有人的共同阶层:

@Entity
@Table(name = "persons")
@DiscriminatorColumn(name = "type")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)

public class Person extends BaseObject {
    private List<Family> families;

    @ManyToMany(cascade=CascadeType.ALL)  
    @ManyToMany(cascade=CascadeType.ALL)
@JoinTable(name="persons_families", joinColumns=@JoinColumn(name="person_id"), inverseJoinColumns=@JoinColumn(name="family_id"))
    public List<Family> getFamilies() {
        return families;
    }

Child和Other以及Parent类是相同的:

@Entity
@Table(name = "persons")
@DiscriminatorValue(value = "children")
public class Child extends Person {}

@Entity
@Table(name = "persons")
@DiscriminatorValue(value = "others")
public class Other extends Person {}

@Entity
@Table(name = "persons")
@DiscriminatorValue(value = "parents")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public class Parent extends Person {}

现在在系统启动期间我遇到以下问题:

org.hibernate.MappingException: Repeated column in mapping for entity: org.parafia.model.Other column: type (should be mapped with insert="false" update="false")

我该怎么办?我的模型有意义吗?

祝你好运

1 个答案:

答案 0 :(得分:1)

  

我的模型有意义吗?

它没有:如果你的目标是,例如,爱丽丝是某个家庭的母亲,也是其他人的孩子,那么type中爱丽丝的persons行应该是什么? Alice应该是Parent还是Child的实例?

子类必须是分离集。