I am using Spring JPA for database access. I am able to find examples such as findByName and countByName, for which I dont have to write any method implementation. I am hoping to find examples for delete a group of records based on some condition.
Does Spring JPA support deleteByName-like delete? Any pointer is appreciated.
Regards and thanks.
If you take a look at the source code of Spring Data JPA, and particularly the
PartTreeJpaQuery
class, you will see that is tries to instantiatePartTree
. Inside that class the following regular expressionprivate static final Pattern PREFIX_TEMPLATE = Pattern.compile("^(find|read|get|count|query)(\\p{Lu}.*?)??By")
should indicate what is allowed and what's not.
Of course if you try to add such a method you will actually see that is does not work and you get the full stacktrace.
I should note that I was using looking at version
1.5.0.RELEASE
of Spring Data JPA2 ways:-
1st one Custom Query
2nd one JPA Query by method
When you go with query by method (2nd way) it will first do a get call
Then it will load it in a List Then it will call delete id one by one
First fetch list of object, then for loop to delete id one by one
But, the 1st option (custom query),
It's just a single query It will delete wherever the value exists.
Go through this link too https://www.baeldung.com/spring-data-jpa-deleteby
Derivation of delete queries using given method name is supported starting with version 1.6.0.RC1 of Spring Data JPA. The keywords
remove
anddelete
are supported. As return value one can choose between the number or a list of removed entities.Be carefull when you use derived query for batch delete. It isn't what you expect: DeleteExecution
Deprecated answer (Spring Data JPA <=1.6.x):
@Modifying
annotation to the rescue. You will need to provide your custom SQL behaviour though.Update:
In modern versions of Spring Data JPA (>=1.7.x) query derivation for
delete
,remove
andcount
operations is accessible.If you will use pre defined delete methods as directly provided by spring JPA then below two queries will be execute by the framework.
First collect data(like id and other column) using by execute select query with delete query where clause.
then after getting resultSet of first query, second delete queries will be execute for all id(one by one)
Note : This is not optimized way for your application because many queries will be execute for single MYSQL delete query.
This is another optimized way for delete query code because only one delete query will execute by using below customized methods.