I have following classes in ont to one relationship.
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;
}
and
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;
}
Now when I try to delete driving license entity then its not deleting it, I am confused, how to delete driving license individually?
entityManager.getTransaction().begin();
DrivingLicense drivingLicense = entityManager.find(DrivingLicense.class, 6);
entityManager.remove(drivingLicense);
entityManager.getTransaction().commit();
instead of deleting its firing below two selects
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=?
why these 2 selects are fired?
Try removing the drivingLicense
from its respective Person
first:
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();