JPA中的继承:如何使用相同的ID

时间:2016-05-10 10:06:28

标签: java jpa

我有一个基类Person和3个类,它们继承自Person。这里有一些简短的片段:

@Entity
public class Person extends Model{

    // ATTRIBUTES
    @Id
    @Column(columnDefinition = "integer")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    @Column(columnDefinition = "varchar(20) not null")
    protected String firstName;
    @Column(columnDefinition = "varchar(20) not null")
    protected String lastName;
    @Column(columnDefinition = "varchar(20) not null")
    protected String password;
    @Column(columnDefinition = "varchar(50) not null")
    protected String eMail;

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Boss extends Person {

    // ATTRIBUTES
    @Column(insertable = false, updatable = false)
    private String dtype;
    @OneToMany(mappedBy = "boss")
    private List<Employee> listEmployee;

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Employee extends Person {

    // ATTRIBUTES
    @Column(insertable = false, updatable = false)
    private String dtype;
    @Column(columnDefinition = "Varchar(20)")
    private String position;
    @ManyToOne
    private Boss boss;

现在我想再次存储员工,老板和员工:

Employee e1 = new Employee(...);
Person p1 = new Person(e1);
Boss b = new Boss(...);
Person p2 = new Person(b);
Employee e2 = new Employee(...);
Person p3 = new Person(e2);
e1.save();
p1.save();
b.save();
p2.save();
e2.save();
p3.save();

这将在员工中生成2个条目,ID为1和2,1个条目在老板中,ID为1,3个条目在人员中,ID为1,2和3。 e1在Employee中为id 1,在Person中为id 1,boss在Boss中为id 1,在Person中为id 2,e2在Employee中为id 2,在Person中为id 3。

是否可以插入一个Employee,它在Employee和Person中具有相同的id而不在我的程序中使用全局计数器?

谢谢

帕特里克

1 个答案:

答案 0 :(得分:0)

您不需要创建和持久化Person的实例 - 实际上Person应该是一个抽象类。鉴于正确的映射(您目前没有),您需要的是以下内容:

Employee e1 = new Employee(...);
Boss b = new Boss(...);
Employee e2 = new Employee(...);

e1.save();
b.save();
e2.save();

在您的映射中,移除@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)表单Boss和Employee并将其添加到person类。

此外,您不需要TABLE_PER_CLASS的Discrimator,因此您可以从Boss和Employee中删除以下内容:

@Column(insertable = false, updatable = false) private String dtype;