Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Persistence Exception foreign key contraint fails in hibernate

I have defined the following two classes in hibernate

@Entity
public class Person {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String name;
 
}

@Entity
public class PhoneNumber {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    @ManyToOne(cascade = CascadeType.ALL)
    private Person person;
 
}

When I persist a phone number object or a person object it’s getting inserted properly.
But when I do

 Person person = session.get(Person.class,1);
        session.remove(person);
        transaction.commit();

I get the foreign key violation exception. But since I have declared a column as ManyToOne shouldn’t hibernate automatically delete the corresponding phonnumber records?

I am not sure if I need to add any extra code to do that

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You have a bi-directional relationship, that is why you have to add the PhoneNumbers in your Person too. And use the mappedBy attribute to show that the Person is the inverse side and whenever it is deleted, please delete every phone number also.

Like this:

@Entity
public class Person {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String name;

    @OneToMany(mappedBy="person", cascade = CascadeType.ALL)
    private Set<PhoneNumber> phoneNumbers;
 
}

Check this for more information.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading