Hibernate继承,多态保存

问题描述 投票:0回答:1

我有一个类

Person
,有两个子类
Student
Employee

@Entity(name="person")
@Inheritance(strategy = InheritanceType.JOINED)
public class Person implements Serializable {
    @Id
    @GeneratedValue
    private Integer id;
}

@Entity(name="student")
@PrimaryKeyJoinColumn(name="id")
public class Student extends Pessoa implements Serializable {
}

@Entity(name="employee")
@PrimaryKeyJoinColumn(name="id")
public class Employee extends Person implements Serializable {
}

学生也可以是员工,但是当我尝试保存与员工具有相同

id
的学生时,Hibernate 会抛出重复主键异常:

org.hibernate.exception.ConstraintViolationException:键“PRIMARY”的重复条目“142.855.267-71”

Hibernate 正在尝试在数据库中插入一个新人,但我不希望这样。

有没有办法让Hibernate识别出一个人已经存在于数据库中并只保存对该人的引用?

顺便说一句:当我手动插入学生和员工时,一切都很顺利。

java sql hibernate inheritance
1个回答
0
投票

您需要指定表和列映射。以下是每个子类映射的表。

@Entity(name="person")
@Table(name = "PERSON")
@Inheritance(strategy = InheritanceType.JOINED)
public class Person implements Serializable {
    @Id
    @GeneratedValue
    @Column(name = "ID")
    private Integer id;
}

@Entity(name="student")
@Table(name="STUDENT")
@PrimaryKeyJoinColumn(name="id")
public class Student extends Pessoa implements Serializable {
}

@Entity(name="employee")
@Table(name="EMPLOYEE")
@PrimaryKeyJoinColumn(name="id")
public class Employee extends Person implements Serializable {
}
© www.soinside.com 2019 - 2024. All rights reserved.