BAEL-4643: JPA CascadeType.REMOVE vs orphanRemoval

* Adds a test to OrphanRemovalIntegrationTest that expects a PersistenceException
This commit is contained in:
Emmanuel Yasa 2020-11-04 23:38:29 +08:00
parent 3139be9468
commit bc501e36b3
2 changed files with 20 additions and 3 deletions

View File

@ -34,6 +34,10 @@ public class OrderRequest {
lineItems.remove(lineItem);
}
public void setLineItems(List<LineItem> lineItems) {
this.lineItems = lineItems;
}
protected OrderRequest() {
}
}

View File

@ -1,12 +1,13 @@
package com.baeldung.jpa.removal;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Before;
import org.junit.Test;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceException;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
@ -19,8 +20,8 @@ public class OrphanRemovalIntegrationTest {
private static EntityManagerFactory factory;
private static EntityManager entityManager;
@BeforeClass
public static void setup() {
@Before
public void setup() {
factory = Persistence.createEntityManagerFactory("jpa-h2-removal");
entityManager = factory.createEntityManager();
}
@ -41,6 +42,18 @@ public class OrphanRemovalIntegrationTest {
Assert.assertEquals(2, findAllLineItem().size());
}
@Test(expected = PersistenceException.class)
public void whenLineItemsIsReassigned_thenThrowAnException() {
createOrderRequestWithLineItems();
OrderRequest orderRequest = entityManager.find(OrderRequest.class, 1L);
orderRequest.setLineItems(new ArrayList<>());
entityManager.getTransaction().begin();
entityManager.merge(orderRequest);
entityManager.getTransaction().commit();
}
private void createOrderRequestWithLineItems() {
List<LineItem> lineItems = new ArrayList<>();
lineItems.add(new LineItem("line item 1"));