JPA / Hibernate Cascade Types - CascadeType.PERSIST

In this post, we will discuss the usage of JPA CascadeType.PERSIST with an example.

Cascading is the way to achieve this. When we perform some action on the target entity, the same action will be applied to the associated entity.

JPA Cascade Types:

All JPA-specific cascade operations are represented by the javax.persistence.CascadeType enum containing entries:

  • ALL - cascades all entity state transitions
  • PERSIST - cascades the entity persist operation.
  • MERGE - cascades the entity merge operation.
  • REMOVE - cascades the entity remove operation.
  • REFRESH - cascades the entity refresh operation.
  • DETACH - cascades the entity detach operation.

Hibernate Cascade Types:

Hibernate supports three additional Cascade Types along with those specified by JPA. These Hibernate-specific Cascade Types are available in org.hibernate.annotations.CascadeType:
  • SAVE_UPDATE - cascades the entity saveOrUpdate operation.
  • REPLICATE - cascades the entity replicate operation.
  • LOCK - cascades the entity lock operation.

JPA / Hibernate Cascade Types - CascadeType.PERSIST

The persist operation makes a transient instance persistent. CascadeType PERSIST propagates the persist operation from a parent to a child entity. When we save the person entity, the phone entity will also get saved.

Consider we have Person and Phone JPA entities:
@Entity
public class Person {

    @Id
    private Long id;

    private String name;

    @OneToMany(mappedBy = "owner", cascade = CascadeType.ALL)
    private List < Phone > phones = new ArrayList < > ();

    //Getters and setters are omitted for brevity

    public void addPhone(Phone phone) {
        this.phones.add(phone);
        phone.setOwner(this);
    }
}


@Entity
public class Phone {

    @Id
    private Long id;

    @Column(name = "`number`")
    private String number;

    @ManyToOne(fetch = FetchType.LAZY)
    private Person owner;

    //Getters and setters are omitted for brevity
}

CascadeType.PERSIST

The CascadeType.PERSIST allows us to persist a child entity along with the parent one.

CascadeType.PERSIST example

Person person = new Person();
person.setId( 1L );
person.setName( "John Doe" );

Phone phone = new Phone();
phone.setId( 1L );
phone.setNumber( "123-456-7890" );

person.addPhone( phone );

entityManager.persist( person );
The above hibernate code prints following SQL statements at the console:
INSERT INTO Person ( name, id )
VALUES ( 'John Doe', 1 )

INSERT INTO Phone ( `number`, person_id, id )
VALUE ( '123-456-7890', 1, 1 )
From above SQL statements proves that when Person persist into a database it also persists it's child Phone object.

References

Comments