Spring Data: supported by "delete by"?

I am using Spring JPA to access the database. I can find examples like findByName and countByName, for which I do not need to write any implementation of the method. I hope to find examples for deleting a group of records based on some condition.

Does Spring JPA support deleteByName-delete? Any pointer is evaluated.

With respect and gratitude.

+54
spring spring-data spring-data-jpa
May 18 '14 at 14:31
source share
3 answers

Deprecated answer (Spring JPA Data <= 1.6.x):

@Modifying annotation for salvation. However, you will need to provide your custom SQL behavior.

 @Transactional(readOnly = true) public interface UserRepository extends JpaRepository<User, Long> { @Modifying @Transactional @Query("delete from User u where u.firstName = ?1") void deleteUsersByFirstName(String firstName); } 

Update:

In modern versions of Spring, JPA data output (> = 1.7.x) for delete , remove and count operations is available.

 public interface UserRepository extends CrudRepository<User, Long> { Long countByFirstName(String firstName); @Transactional Long deleteByFirstName(String firstName); @Transactional List<User> removeByFirstName(String firstName); } 
+104
May 18 '14 at 15:35
source share
— -

Approval of deletion requests using the name of this method is supported since version 1.6.0.RC1 of the JPA data Spring. The keywords remove and delete supported. You can choose between a number or a list of deleted objects as the return value.

 Long removeByLastname(String lastname); List<User> deleteByLastname(String lastname); 
+44
May 19 '14 at 6:31
source share

If you look at the source code for Spring Data JPA, and especially the PartTreeJpaQuery class, you will see that it is trying to create an instance of PartTree . Inside this class, the following regular expression

private static final Pattern PREFIX_TEMPLATE = Pattern.compile("^(find|read|get|count|query)(\\p{Lu}.*?)??By")

must indicate what is allowed and what is not.

Of course, if you try to add such a method, you will see that this does not work, and you will get a full stack.

It should be noted that I used version 1.5.0.RELEASE for Spring Data JPA

+2
May 18 '14 at 15:46
source share



All Articles