Andrei Pall

Linux Software Engineering

JPA Cascade Types Explained with Examples

In Java Persistence API (JPA), cascade types define which operations performed on a parent entity should automatically propagate to its associated child entities.

Although they’re often called JPQL cascade types, cascading is actually a feature of JPA entity relationships, not JPQL itself.

JPA provides six cascade types, defined in jakarta.persistence.CascadeType.

1. All JPA cascade types

Cascade type Description
PERSIST Automatically persists associated entities when the parent is persisted.
MERGE Automatically merges associated entities when the parent is merged.
REMOVE Automatically removes associated entities when the parent is removed.
REFRESH Automatically refreshes associated entities when the parent is refreshed.
DETACH Automatically detaches associated entities when the parent is detached.
ALL Includes all five operations above.

These cascade types can be configured on relationships such as @OneToOne, @OneToMany, @ManyToOne, and @ManyToMany.

2. Example entities

We’ll use two entities throughout the examples:

  • Department — the parent entity.
  • Employee — the child entity.

One department can have multiple employees, while each employee belongs to one department.

One-to-many relationship: Department → Employees

Department.java

import jakarta.persistence.*;
import java.util.ArrayList;
import java.util.List;

@Entity
public class Department {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    @OneToMany(
        mappedBy = "department",
        cascade = CascadeType.ALL
    )
    private List<Employee> employees = new ArrayList<>();

    public void addEmployee(Employee employee) {
        employees.add(employee);
        employee.setDepartment(this);
    }

    // Getters and setters
}

Employee.java

import jakarta.persistence.*;

@Entity
public class Employee {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    @ManyToOne
    @JoinColumn(name = "department_id")
    private Department department;

    // Getters and setters
}

For the following examples, assume that we change cascade = CascadeType.ALL to the cascade type being demonstrated.

3. CascadeType.PERSIST

Purpose: Automatically saves new associated entities when their parent is persisted.

Without cascading, you would normally need to persist the parent and child entities individually.

Configuration

@OneToMany(
    mappedBy = "department",
    cascade = CascadeType.PERSIST
)
private List<Employee> employees = new ArrayList<>();

Example

Department department = new Department();
department.setName("IT");

Employee employee1 = new Employee();
employee1.setName("John");

Employee employee2 = new Employee();
employee2.setName("Alice");

department.addEmployee(employee1);
department.addEmployee(employee2);

entityManager.getTransaction().begin();

entityManager.persist(department);

entityManager.getTransaction().commit();

What happens?

When entityManager.persist(department) executes:

  1. JPA persists the Department.
  2. JPA automatically persists employee1.
  3. JPA automatically persists employee2.

The database will contain:

department

id name
1 IT

employee

id name department_id
1 John 1
2 Alice 1

The SQL generated by the persistence provider will be similar to:

INSERT INTO department (name)
VALUES ('IT');

INSERT INTO employee (name, department_id)
VALUES ('John', 1);

INSERT INTO employee (name, department_id)
VALUES ('Alice', 1);

Without CascadeType.PERSIST, you would generally need to persist the new employees explicitly:

entityManager.persist(department);
entityManager.persist(employee1);
entityManager.persist(employee2);

When to use: When creating a parent entity should automatically create its new child entities.

4. CascadeType.MERGE

Purpose: Automatically propagates merge operations to associated entities.

This is particularly useful when working with detached entities.

Configuration

@OneToMany(
    mappedBy = "department",
    cascade = CascadeType.MERGE
)
private List<Employee> employees = new ArrayList<>();

Example

Assume that the department and its employees already exist in the database.

Department department = entityManager.find(
    Department.class, 1L
);

// Initialize employees while managed
department.getEmployees().size();

// Detach the department and employees
entityManager.clear();

// Modify detached entities
department.setName("Software Development");

Employee employee = department.getEmployees().get(0);
employee.setName("John Smith");

entityManager.getTransaction().begin();

Department managedDepartment =
    entityManager.merge(department);

entityManager.getTransaction().commit();

What happens?

  1. JPA merges the detached department state into a managed entity.
  2. Because of CascadeType.MERGE, JPA also merges its associated employees.
  3. The modified values are synchronized with the database when the persistence context is flushed.

The SQL might look like:

UPDATE department
SET name = 'Software Development'
WHERE id = 1;

UPDATE employee
SET name = 'John Smith'
WHERE id = 1;

Important: merge() returns a managed entity. The original detached object remains detached.

Department managed = entityManager.merge(department);

// managed is managed
// department remains detached

Also, merge() does not necessarily execute an SQL UPDATE immediately.

When to use: When detached parent entities and their associated entities need to be merged together.

5. CascadeType.REMOVE

Purpose: Automatically deletes associated child entities when their parent is removed.

Configuration

@OneToMany(
    mappedBy = "department",
    cascade = CascadeType.REMOVE
)
private List<Employee> employees = new ArrayList<>();

Example

entityManager.getTransaction().begin();

Department department = entityManager.find(
    Department.class, 1L
);

entityManager.remove(department);

entityManager.getTransaction().commit();

What happens?

JPA removes the department and cascades the removal to its employees.

Before:

department

id name
1 IT

employee

id name department_id
1 John 1
2 Alice 1

After the operation, the department and both employees are deleted.

Typical SQL:

DELETE FROM employee WHERE id = 1;
DELETE FROM employee WHERE id = 2;
DELETE FROM department WHERE id = 1;

The provider normally handles the necessary ordering to satisfy foreign-key constraints.

Be careful with CascadeType.REMOVE.

Removing a department will also remove all associated employees. Use it only when deleting the parent should genuinely delete the children.

When to use: When child entities have a lifecycle dependent on their parent, such as order items belonging exclusively to an order.

6. CascadeType.REFRESH

Purpose: Reloads the state of an entity and its associated entities from the database, discarding their unflushed in-memory modifications.

Configuration

@OneToMany(
    mappedBy = "department",
    cascade = CascadeType.REFRESH
)
private List<Employee> employees = new ArrayList<>();

Example

Department department = entityManager.find(
    Department.class, 1L
);

Employee employee = department.getEmployees().get(0);

// Modify the entities in memory
department.setName("Temporary Department");
employee.setName("Temporary Employee");

// Refresh the parent
entityManager.refresh(department);

What happens?

Assume the database currently contains:

Entity Database value
Department IT
Employee John

Before refresh():

department.getName(); // "Temporary Department"
employee.getName();   // "Temporary Employee"

After refresh():

department.getName(); // "IT"
employee.getName();   // "John"

Both entities are refreshed because CascadeType.REFRESH is enabled.

Without cascading, refreshing the department would not automatically refresh the employee.

Important: Refresh can discard pending changes. It should not be used as a general replacement for transaction rollback.

When to use: When you need to reload the parent and associated entities from the database, for example after an external process has updated their records.

7. CascadeType.DETACH

Purpose: Automatically detaches associated entities from the persistence context when the parent is detached.

Detached entities are no longer tracked for automatic database synchronization.

Configuration

@OneToMany(
    mappedBy = "department",
    cascade = CascadeType.DETACH
)
private List<Employee> employees = new ArrayList<>();

Example

Department department = entityManager.find(
    Department.class, 1L
);

Employee employee = department.getEmployees().get(0);

entityManager.detach(department);

// Both entities are detached
System.out.println(
    entityManager.contains(department)
); // false

System.out.println(
    entityManager.contains(employee)
); // false

What happens?

Before detach:

Department

Managed

Employee

Managed

entityManager.detach(department)

Department

Detached

Employee

Detached

Now modifying the objects will not automatically generate database updates:

department.setName("New Name");
employee.setName("New Employee Name");

The modifications will remain in memory unless the state is later merged or otherwise explicitly synchronized.

When to use: When you intentionally want to stop tracking a parent and its associated entities, such as when passing detached objects to another application layer.

8. CascadeType.ALL

Purpose: Enables all five cascade operations.

Configuration

@OneToMany(
    mappedBy = "department",
    cascade = CascadeType.ALL
)
private List<Employee> employees = new ArrayList<>();

It is equivalent to:

@OneToMany(
    mappedBy = "department",
    cascade = {
        CascadeType.PERSIST,
        CascadeType.MERGE,
        CascadeType.REMOVE,
        CascadeType.REFRESH,
        CascadeType.DETACH
    }
)
private List<Employee> employees = new ArrayList<>();

Example

Department department = new Department();
department.setName("IT");

Employee employee = new Employee();
employee.setName("John");

department.addEmployee(employee);

entityManager.getTransaction().begin();

// Saves department and employee
entityManager.persist(department);

entityManager.getTransaction().commit();

Later:

entityManager.getTransaction().begin();

Department department = entityManager.find(
    Department.class, 1L
);

// Deletes department and employees
entityManager.remove(department);

entityManager.getTransaction().commit();

With CascadeType.ALL, persist(), merge(), remove(), refresh(), and detach() all cascade to the associated entities.

When to use: When child entities are completely dependent on the parent entity and should share its persistence lifecycle.

9. Multiple cascade types

You do not need to use only one cascade type or CascadeType.ALL.

You can combine individual cascade types.

For example:

@OneToMany(
    mappedBy = "department",
    cascade = {
        CascadeType.PERSIST,
        CascadeType.MERGE
    }
)
private List<Employee> employees = new ArrayList<>();

This configuration means:

Operation Cascades to employees?
persist() Yes
merge() Yes
remove() No
refresh() No
detach() No

This is useful when employees should be automatically created or merged with their department, but deleting a department should not automatically delete the employees.

However, removing the department may still fail due to foreign-key constraints unless its employee associations are reassigned, cleared appropriately, or otherwise handled.

10. CascadeType.REMOVE vs orphanRemoval = true

One important JPA feature closely related to cascading is orphanRemoval.

It is not a cascade type, but it is commonly used with @OneToMany and @OneToOne.

Configuration

@OneToMany(
    mappedBy = "department",
    cascade = CascadeType.ALL,
    orphanRemoval = true
)
private List<Employee> employees = new ArrayList<>();

Difference

CascadeType.REMOVE deletes children when their parent is deleted.

orphanRemoval = true deletes a child when it is removed from the relationship, even if the parent remains.

Example with orphanRemoval

entityManager.getTransaction().begin();

Department department = entityManager.find(
    Department.class, 1L
);

Employee employee = department.getEmployees().get(0);

department.getEmployees().remove(employee);
employee.setDepartment(null);

entityManager.getTransaction().commit();

Because orphanRemoval = true, JPA deletes the employee from the database.

Expected SQL:

DELETE FROM employee
WHERE id = 1;

The department remains in the database.

Comparison

Operation CascadeType.REMOVE orphanRemoval = true
Delete parent using remove() Deletes children Deletes children
Remove child from parent’s collection Does not delete child by itself Deletes orphaned child
Parent remains in database Not when parent is removed Yes, when removing only a child
Typical use Parent deletion propagation Privately owned child lifecycle

Important: orphanRemoval = true should generally be used only when the child is exclusively owned by the parent. Removing a child from the collection is not the same as deleting a shared entity.

11. Cascading with different relationship types

Cascade types work with different JPA relationships, but the appropriate configuration depends on the relationship.

Relationship Common configuration Recommendation
@OneToOne ALL Appropriate for exclusively owned child entities
@OneToMany PERSIST, MERGE, optionally REMOVE Depends on child ownership
@ManyToOne Usually no cascade Avoid deleting shared parent entities
@ManyToMany Sometimes PERSIST, MERGE Generally avoid REMOVE

Example: @OneToOne

@Entity
public class User {

    @Id
    @GeneratedValue
    private Long id;

    @OneToOne(cascade = CascadeType.ALL)
    private UserProfile profile;
}

When a user is persisted, its profile is also persisted. When the user is removed, the profile is also removed.

This is appropriate if the profile belongs exclusively to that user.

Example: @ManyToOne

@Entity
public class Employee {

    @Id
    @GeneratedValue
    private Long id;

    @ManyToOne
    @JoinColumn(name = "department_id")
    private Department department;
}

Notice that no cascade type is specified.

This is generally preferable because multiple employees can reference the same department.

If CascadeType.REMOVE were configured on this relationship, deleting an employee could also attempt to delete the department.

That is usually undesirable.

Example: @ManyToMany

@Entity
public class Student {

    @Id
    @GeneratedValue
    private Long id;

    @ManyToMany(
        cascade = {
            CascadeType.PERSIST,
            CascadeType.MERGE
        }
    )
    private Set<Course> courses = new HashSet<>();
}

Here, new courses may be persisted and detached courses merged when the corresponding operation is performed on a student.

Avoid CascadeType.REMOVE when courses are shared by multiple students.

Deleting one student should not delete courses that other students are enrolled in.

12. Important: JPQL DELETE and UPDATE do not trigger cascades

This is a particularly important distinction.

JPA cascade operations are triggered by entity lifecycle operations, not by bulk JPQL statements.

For example:

entityManager.remove(department);

This triggers CascadeType.REMOVE.

However:

entityManager.createQuery(
    "DELETE FROM Department d WHERE d.id = :id"
)
.setParameter("id", 1L)
.executeUpdate();

Does not trigger CascadeType.REMOVE.

JPQL bulk deletes operate directly on database rows and bypass entity-level cascade processing.

This can cause foreign-key constraint violations if child records still reference the deleted department.

The same principle applies to bulk JPQL UPDATE statements: they do not trigger entity cascade operations or normal entity lifecycle synchronization.

Database-level ON DELETE CASCADE constraints are a separate mechanism and may still apply.

13. Complete summary

Cascade type Triggering JPA operation Effect on associated entities
PERSIST entityManager.persist(parent) Persists new children
MERGE entityManager.merge(parent) Merges children
REMOVE entityManager.remove(parent) Removes children
REFRESH entityManager.refresh(parent) Reloads children from database
DETACH entityManager.detach(parent) Detaches children
ALL All five operations Propagates all five operations
  1. Use PERSIST and MERGE when parent and child entities should be created or merged together.
  2. Use REMOVE carefully, particularly when multiple entities may share the same child or parent.
  3. Use orphanRemoval = true for child entities that should be deleted when removed from an exclusively owned relationship.
  4. Avoid CascadeType.ALL on @ManyToMany relationships because it includes REMOVE.
  5. Avoid cascading from @ManyToOne to shared parent entities unless there is a specific lifecycle reason.
  6. Remember that JPQL bulk DELETE and UPDATE bypass JPA cascading.

For most applications, the safest approach is to configure only the cascade types you actually need rather than automatically using CascadeType.ALL everywhere.