In JPA, to delete an entity, the entity itself must be managed, meaning that it is present in the persistence context. This means that the calling application should have already loaded or accessed the entity and is now issuing a command to remove it.
This is not normally a problem given that most often the application will have caused it to become managed as part of the process of determining that this was the object that it wanted to remove.
1. JPA delete entity with EntityManager.remove()
Java program showing JPA delete entity by id.
@ContextConfiguration(locations = "classpath:application-context-test.xml") @RunWith(SpringJUnit4ClassRunner.class) public class TestRemoveEntity { @PersistenceContext private EntityManager manager; private static Integer departmentId; @Before public void setupData() { DepartmentEntity department = new DepartmentEntity("Information Technology"); manager.persist(department); departmentId = department.getId(); } @Test @Transactional @Rollback(true) public void testRemoveDepartment() { //Find managed Entity reference DepartmentEntity department = manager.find(DepartmentEntity.class, departmentId); //Call remove method to remove the entity if(department != null){ manager.remove(department); } List<DepartmentEntity> departments = manager.createQuery("Select a From DepartmentEntity a", DepartmentEntity.class).getResultList(); Assert.assertEquals(0, departments.size()); } }
In this example, we are first finding the entity using the find()
call, which returns a managed instance of DepartmentEntity
, and then removing the entity using the remove()
call on the entity manager.
This method will ensure that the department with the given id, provided the id is not null, is removed from the database. It will return successfully whether the department exists or not.
2. JPA delete multiple entities with JPQL Query
Another way to remove entity is using JPQL (Java Persistence Query Language) in below manner. It can help to delete multiple rows with single statement.
//Delete entity using JP QL Query query = manager.createNativeQuery("DELETE FROM DEPARTMENT WHERE ID = " + departmentId); query.executeUpdate();
In fact, in this way you remove multiple rows in single query, which is not possible using EntityManager.remove()
method.
//Delete all rows in single query Query query = manager.createNativeQuery("DELETE FROM DEPARTMENT"); query.executeUpdate();
Above code is built and tested using sourcecode provided for this tutorial.
Happy Learning !!