Hibernate one to one mapping. Delete row from dependent table

2.3k Views Asked by At

Tables : Student, Address Student.ADDR_ID column maps to Address.ID

Annotation in my Student class is as follows

public class Student {

String name, surname;
int rollNumber;
Teacher classTeacher;
Address address;

@OneToOne(cascade=CascadeType.ALL)
@JoinColumn(name="ADDR_ID")
public Address getAddress() {
    return address;
}
:
:

It is working fine in create and update case.

If I change the address of Student to a new then it creates a new row but does not delete the row for old address. If I set address to null still it does not delete

e.g.

 Student s1 = session.get(Student.class, 24);
 Address addr = new Address();
 session.save(addr);
 s1.setAddress(addr);
 session.save(s1);

 or

 Student s1 = session.get(Student.class, 24);
 s1.setAddress(null);

I have set cascade ALL. What extra/different needs to be done. Is Inverse applicable here ?

2

There are 2 best solutions below

1
On

You should use orphanremoval = true if that suffice for you

@OneToOne(cascade=CascadeType.ALL, orphanRemoval=true)
@JoinColumn(name="ADDR_ID")
public Address getAddress() {
}
0
On

In my case One to one delete cascade was not working because of Transaction is not used. Here it is working fine...

@Entity
@Table(name="student")
public class Student {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id")
    private Long id;

    @Column(name="student_name",length=60)
    private String studentName;

    @OneToOne(cascade=CascadeType.ALL)
    @JoinColumn(name = "address_id")
    private Address address;

    //Setter Getter
}

@Entity
@Table(name = "address_table")
public class Address {

    @Id
    @Column(name = "address_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long addressId;

    @Column(name = "street_name", length = 50)
    private String street;

    @Column(name = "city_name", length = 50)
    private String city;

    //Setter Getter
}


Student student = session.get(Student.class, 1L);
session.beginTransaction();
session.delete(employee);
session.getTransaction().commit();