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); lineItems.remove(lineItem);
} }
public void setLineItems(List<LineItem> lineItems) {
this.lineItems = lineItems;
}
protected OrderRequest() { protected OrderRequest() {
} }
} }

View File

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