Cascade Type PERSIST propagates the persist operation from a parent to a child entity. When we save the person entity, the address entity will also get saved.
Example
Person.java
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Entity
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
@OneToMany(mappedBy = "person", cascade = CascadeType.PERSIST)
private List<Address> addresses;
}
Address.java
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Entity
public class Address {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String street;
private int houseNumber;
private String city;
private int zipCode;
@ManyToOne(fetch = FetchType.LAZY)
private Person person;
}
Test.java
class Demo11ApplicationTests {
private static final SessionFactory sessionFactory;
static {
try {
sessionFactory = new Configuration()
.configure()
.buildSessionFactory();
} catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
}
@Test
public void whenParentSavedThenChildSaved() {
Session session = sessionFactory.openSession();
session.beginTransaction();
Person person = Person.builder()
.name("peter")
.build();
Address address = Address.builder()
.houseNumber(40)
.build();
address.setPerson(person);
person.setAddresses(Arrays.asList(address));
// only save the parent entity
session.persist(person);
session.flush();
assertNotNull(person.getId());
assertNotNull(address.getId());
session.close();
}
}
resources/hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property>
<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">create-drop</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="hibernate.connection.pool_size">100</property>
<!-- Disable the second-level cache -->
<property name="hibernate.cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<mapping class="com.example.demo11.Person" />
<mapping class="com.example.demo11.Address" />
</session-factory>
</hibernate-configuration>