在双向OneToOne关系中删除子实体

时间:2015-10-09 04:50:25

标签: hibernate jpa one-to-one

我有以下几个关系的课程。

DrivingLicense.java
@Entity
@Table(name = "DRIVING_LICENSE")
public class DrivingLicense {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "LICENSE_NUMBER")
    private int licenseNumber;
    @Column(name = "DATE_OF_ISSUE")
    private Date dateOfIssue;

    @OneToOne
    @JoinColumn(name = "PERSON_ID")
    private Person person;
}

Person.java
@Entity
@Table(name = "PERSON")
public class Person {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "PERSON_ID")
    private int personId;
    @Column(name = "PERSON_NAME", nullable = false, length = 30)
    private String personName;

    @OneToOne(mappedBy = "person", cascade = CascadeType.ALL)
    private DrivingLicense drivingLicense;
}

现在,当我尝试删除驾驶执照实体,然后不删除它时,我很困惑,如何单独删除驾驶执照?

    entityManager.getTransaction().begin();

    DrivingLicense drivingLicense = entityManager.find(DrivingLicense.class, 6);
    entityManager.remove(drivingLicense);
    entityManager.getTransaction().commit();

更新

而不是在两个选择

之下删除它
Hibernate: select drivinglic0_.LICENSE_NUMBER as LICENSE_NUMBER1_0_0_, drivinglic0_.DATE_OF_ISSUE as DATE_OF_ISSUE2_0_0_, drivinglic0_.PERSON_ID as PERSON_ID3_0_0_, person1_.PERSON_ID as PERSON_ID1_1_1_, person1_.PERSON_NAME as PERSON_NAME2_1_1_ from DRIVING_LICENSE drivinglic0_ left outer join PERSON person1_ on drivinglic0_.PERSON_ID=person1_.PERSON_ID where drivinglic0_.LICENSE_NUMBER=?
Hibernate: select drivinglic0_.LICENSE_NUMBER as LICENSE_NUMBER1_0_1_, drivinglic0_.DATE_OF_ISSUE as DATE_OF_ISSUE2_0_1_, drivinglic0_.PERSON_ID as PERSON_ID3_0_1_, person1_.PERSON_ID as PERSON_ID1_1_0_, person1_.PERSON_NAME as PERSON_NAME2_1_0_ from DRIVING_LICENSE drivinglic0_ left outer join PERSON person1_ on drivinglic0_.PERSON_ID=person1_.PERSON_ID where drivinglic0_.PERSON_ID=?

为什么这两个选择会被解雇?

1 个答案:

答案 0 :(得分:1)

首先尝试从drivingLicense Person删除entityManager.getTransaction().begin(); DrivingLicense drivingLicense = entityManager.find(DrivingLicense.class, 6); Person person = drivingLicense.getPerson(); person.setDrivingLicense(null); entityManager.merge(person); entityManager.remove(drivingLicense); entityManager.getTransaction().commit();

{{1}}