Luc*_*cao 5 java sql inheritance hibernate
I have a class Person with two subclasses Student and 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 {
}
Run Code Online (Sandbox Code Playgroud)
A student can also be an employee, but when I try to save a student with the same id as an employee, hibernate throws a duplicate primary key exception
org.hibernate.exception.ConstraintViolationException: Duplicate entry '142.855.267-71' for key 'PRIMARY'
Run Code Online (Sandbox Code Playgroud)
hibernate is trying to insert a new person in the database, and I don't want that.
Is there a way to make hibernate recognize that a person already exists in the database and just save the reference to the person?
btw: when I insert a student and an employee manually everything works like a charm.
您需要指定表和列映射。以下是每个子类映射的表。
@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 {
}
Run Code Online (Sandbox Code Playgroud)