Delete Example in JPA

By | | Updated : 2021-01-22 | Viewed : 196 times

jpa delete query example

In this current tutorial, we will learn how many ways to delete the entity in JPA.

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.

remove() In JPA
transaction = entityManager.getTransaction();
transaction.begin();

Player player = entityManager.find(Player.class, 1000002l);
entityManager.remove(player);

transaction.commit();

Delete Query In Jpa

delete query In jpa
Query query = entityManager.createQuery("DELETE from Player p where p.id = :id");
query.setParameter("id", 1000007l);
query.executeUpdate();

Here used Query class object is created with required for deletion. and applied query execution with query executeUpdate() method.

delete all records in table

Delete all records in the 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

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

Leave A Reply