javahibernatejpacascadeentities

Cascades settings in JPA and foreign key violation in hibernate


I have tow classes:

  1. Parent
  2. Child

In the database Child table has a column ParentId -> typical One (Parent) -> Many (Children) relation

Now I create two entities and they

public class Parent
{
    @OneToMany(mappedBy="Parent", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    public Set<Child> getChildern()
    {
      ...
    }
}

public class Child
{
   @ManyToOne(fetch = FetchType.EAGER, cascade=CascadeType.ALL)
   @JoinColumn(name="ParentId")
   public Parent getParent()
   { ... }
}

Now I have two scenarios:

  1. Parent gets deleted -> what should happen?
  2. Child gets deleted -> what should happen?

Bonus questions:

  1. Do I always need to create both parts of the key OneToMany and ManyToOne or can i just have ManyToOne and dont care in the parent where I have children?
  2. What could cause a hibernate to give me a message foreign key constraint violation for a parent which has no children?

Solution

  • First of all I'm surprised this code works at all. IMO mappedBy="Parent" should actually be mappedBy="parent" (note the lower-case 'p') because the parent property of the Child class is called parent and not Parent.

    Second, I suggest you place the annotations on the properties rather than on the accessor methods. I find it makes the whole code

    Answers to your questions depend on what exactly you mean by "get deleted". I assume you mean "deleted through persistence manager".

    BUT just in case you expect/want that a child is removed by the JPA provider if you do parent.getChildren().remove(x) then you need to set orphanRemoval = "true" on OneToMany.

    Question 1

    Parent and all children are deleted. That's the common case.

    Question 2

    Parent and all children are deleted. That's a rather odd use case. Usually cascade delete is only applied on the one-to-many relationship.

    Bonus 1

    All relationships in Java and JPA are unidirectional, in that if a source object references a target object there is no guarantee that the target object also has a relationship to the source object.

    from the excellent Java Persistence wiki book.

    Bonus 2

    Dunno. Is the ConstraintViolationException coming from the underlying data base? Or put differently, how does the DDL for the two tables look like? Was it generated by Hibernate?