Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the JPA CascadeType.PERSIST work ?

Tags:

In my example, Employee has an OneToOne relationship to Department with CascadeType.PERSIST. When I persist multiple Employee,


Why does the EntityManager persist a single Department record for all Employee records?


My expectation is, if we use CascadeType.PERSIST, when an Employee is being persisted, a Department record will be created anew for each Employee record.

Employee.java

@Entity
public class Employee {
    private String id;
    private String name;
    @OneToOne(cascade = CascadeType.PERSIST)
    @JoinColumn(name = "DEP_ID", referencedColumnName = "ID")
    private Department department;

    -----
}

Department.java

@Entity
public class Department implements Serializable {
    private String id;
    private String name;
}

Test.java

public void insert() {
    em = emf.createEntityManager();
    em.getTransaction().begin();
    Department department = new Department("Test Department");
    for(int i=1; i <= 10; i++) {
        Employee e = new Employee("EMP" + i, department);
        em.persist(e);
    }
    em.getTransaction().commit();
    em.close();
}

Result :

Employee Table          Department Table
=================       ==============================
ID  Name  DEP_ID        ID      NAME    
=================       ==============================
1   EMP1    1           1       Test Department
2   EMP2    1
3   EMP3    1
4   EMP4    1
5   EMP5    1
6   EMP6    1
7   EMP7    1
8   EMP8    1
9   EMP9    1
10  EMP10   1   
like image 485
Zaw Than oo Avatar asked Oct 16 '12 05:10

Zaw Than oo


People also ask

What does CascadeType persist do?

CascadeType. PERSIST : It means that the save() and persist() operations in the hibernate cascade to the related entities. CascadeType. MERGE : It means that the related entities are joined when the owning entity is joined.

What is CascadeType in JPA?

To establish a dependency between related entities, JPA provides javax. persistence. CascadeType enumerated types that define the cascade operations. These cascading operations can be defined with any type of mapping i.e. One-to-One, One-to-Many, Many-to-One, Many-to-Many.

What does CascadeType detach do?

The detach operation removes the entity from the persistent context. When we use CascadeType. DETACH, the child entity will also get removed from the persistent context.

What is CascadeType merge?

CascadeType. MERGE : cascade type merge means that related entities are merged when the owning entity is merged.


1 Answers

JPA maintains object identity and will not persist an existing object.

Change you code to be correct,

for(int i=1; i <= 10; i++) {
    Department department = new Department("Test Department");
    Employee e = new Employee("EMP" + i, department);
    em.persist(e);
}
like image 153
James Avatar answered Oct 15 '22 06:10

James