Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring data jpa deleteBy query not working

I am trying to create a custom deleteBy method query in my repository. It seems that instead of deleting, hibernate is making a select statement.

public interface ContactRepository extends JpaRepository<Contact, Integer> {      Integer deleteByEmailAddress(String emailAddress);      //and this one works     Contact findContactByName(String name); } 

and here is what Hibernate is trying to do:

Hibernate: select contact0_.id as id1_2_, contact0_.emailAddress as >emailAdd2_2_, contact0_.name as name3_2_ from Contact contact0_ where >contact0_.emailAddress=?

What am I missing? Do I have to make a special configuration in order to make delete work?

like image 644
Alexandru Pirvu Avatar asked Jul 10 '15 16:07

Alexandru Pirvu


People also ask

How do I delete multiple records in JPA?

First of all you need to create a jpa query method that brings all records belong to id. After that you can do deleteAll() operation on List.

How do I delete a record using JPA?

We can use the JPA method deleteById() for deleting the record of the particular primary key.


2 Answers

Is the delete not working or not working as how you'd expect? Typically an entity has to be managed before it can be deleted, so a JPA provider (hibernate in your case) will load (the query you see) the entity first, then issue the delete.

If you're only seeing the query, but no corresponding delete, then some possibilities are:

  1. there's nothing to delete, make sure the record is there in the db
  2. the delete needs to be part of a transaction. I believe the Spring data CRUD ops are transactional by default, if not just make sure whatever is calling deleteByEmailAddress is transactional

Note: you can avoid the select when removing an entity using a modifying query delete, example below:

// NOTE: you have return void @Modifying @Transactional @Query(value="delete from Contact c where c.emailAddress = ?1") void deleteByEmailAddress(String emailAddress) 
like image 173
ikumen Avatar answered Sep 19 '22 22:09

ikumen


In modern versions of Spring Data JPA (>=1.7.x) query derivation for delete, remove and count operations is accessible.

Spring Data: "delete by" is supported?

like image 20
Cristian J. Brito Avatar answered Sep 18 '22 22:09

Cristian J. Brito