无法删除使用查询获取的关联实体

时间:2015-10-09 10:27:02

标签: hibernate jpa

我无法删除使用查询获取的关联实体实例,我有以下类

@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)
    //@Fetch(FetchMode.JOIN)
    private DrivingLicense drivingLicense;
}

@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;
}

我试图删除

entityManager.getTransaction().begin();

List<Person> resultList = entityManager.createQuery("from Person p join fetch p.drivingLicense", Person.class).getResultList();
resultList.forEach(person -> System.out.println(person.getDrivingLicense().getDateOfIssue()));

DrivingLicense drivingLicense = resultList.get(0).getDrivingLicense();
System.out.println(drivingLicense.getLicenseNumber());
entityManager.remove(drivingLicense);


entityManager.getTransaction().commit();

我认为它会删除DrivingLicense,但不会删除它。当我尝试使用entityManager.remove(resultList.get(0))删除Person时,它会将此人与DrivingLicense一起删除。

我知道它是如何工作的?为什么DrivingLIcense没有被删除?

1 个答案:

答案 0 :(得分:1)

或许,您正在获得参照完整性约束错误,因为您没有更新双向关联的另一面。

在删除实体之前尝试更新引用:

Person person = resultList.get(0);
DrivingLicense drivingLicense = person.getDrivingLicense();
drivingLicense.setPerson(null);
person.setDrivingLicense(null);
entityManager.merge(person);
entityManager.remove(entityManager.merge(drivingLicense));