Hibernate CascadeType Issue: Updates not Cascading to Child Entity

26 Views Asked by At

I'm encountering an issue with Hibernate when trying to update a parent entity that has a one-to-one relationship with a child entity. Specifically, I've configured CascadeType.ALL for the relationship, but when I update the parent entity, the changes are not cascading to the associated child entity.

Additional information:

  • I'm using a separate Java module to perform database operations (i.e., I'm not using the DAO model).
  • I properly configured bidirectional mapping between entities.

javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute statement

Here's how I've configured my entities:

@Entity
public class Parent {

    @Id
    private Long id;

    // Other fields and annotations...

    @OneToOne(mappedBy = "parent", cascade = CascadeType.ALL)
    private Child child;

    // Constructors, getters, and setters...
}

@Entity
public class Child {

    @Id
    private Long id;

    // Other fields and annotations...

    @OneToOne
    @JoinColumn(name = "parent_id")
    private Parent parent;

    // Constructors, getters, and setters...
}

What could be causing this issue, and how can I ensure that update is reflected to both parent and child entity are properly cascaded?

Any help or suggestions would be greatly appreciated. Thank you!

Expectation: My expectation is that since the two entities are bidirectionally mapped, when a parent entity is saved to the database, the child entity shall also be saved automatically. Additionally, when updating an existing row with function session.saveOrUpdate(parentEntity), both the parent and child entities should be updated accordingly.

Analysis: session.saveOrUpdate(parentEntity) Above function works fine to create a new row with unique primary key. But when i want to update the data in existing row of same primary key it throws:

1

There are 1 best solutions below

0
meridbt On

Try to swap the owning side:

  1. Put @JoinColumn and @OneToOne(cascade = CascadeType.ALL) above Child field in Parent class
  2. Put @OneToOne(mappedBy = "child") above Parent field in Child class

Are you using ddl-auto to create you database structure? Could you show table create scripts?

Make sure that you really need the bi-directional relationship