Delete Example in JPA
By AmarSivas | | Updated : 2021-01-22 | Viewed : 517 times

In this current tutorial, we will learn how many ways to delete the entity in JPA.
Table of Contents:
remove() In JPA
To delete the entity in JPA we can use the remove() method in JPA. And please find the below-given example snippet code for remove the entity in JPA.
transaction = entityManager.getTransaction();
transaction.begin();
Player player = entityManager.find(Player.class, 1000002l);
entityManager.remove(player);
transaction.commit();
Delete Query In Jpa
Query query = entityManager.createQuery("DELETE from Player p where p.id = :id");
query.setParameter("id", 1000007l);
query.executeUpdate();
Here used
delete all records in table
Query query1 = entityManager.createQuery("DELETE from Player p");
query1.executeUpdate();
Here we can delete all the records in a particular table.
Delete Multiple Records In Table
List idList = new ArrayList();
idList.add(1000008);
idList.add(1000009);
String idParams = idList.stream().map(Object::toString).collect(Collectors.joining(",")).toString();
//To multiple records in JPA
Query query1 = entityManager.createQuery("DELETE from Player p WHERE p.id IN ("+idParams+")");
query1.executeUpdate();
Here we can delete multiple numbers of records in a particular table. Please refer the Github repository JPA-Remove-Example-App-With-XML