Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to shorten names of query methods in Spring Data JPA Repositories?

Consider a Spring Data Jpa Repository:

public interface UserRepository extends JpaRepository<User, Long> {      User findOneByDeletedIsFalseAndActivationKey(String activationKey);      List<User> findAllByDeletedIsFalseAndActivatedIsFalseAndCreatedDateBefore(DateTime dateTime);      User findOneByDeletedIsFalseAndLogin(String login);      User findOneByDeletedIsFalseAndEmail(String email);  } 

Notice each method has "DeletedIsFalse" in it. Is there a simple way to make method names shorter? Like i.e.:

@FullMethodName("findOneByDeletedIsFalseAndEmail") User findOneByEmail(String email); 
like image 944
Igor Mukhin Avatar asked May 03 '15 21:05

Igor Mukhin


People also ask

What are three methods to execute queries in JPA?

There are three basic types of JPA Queries:Query, written in Java Persistence Query Language (JPQL) syntax. NativeQuery, written in plain SQL syntax.

What is the difference between getById and findById?

As a consequence, findById() returns the actual object and getById returns a reference of the entity.

Which is better CrudRepository or JpaRepository?

Crud Repository doesn't provide methods for implementing pagination and sorting. JpaRepository ties your repositories to the JPA persistence technology so it should be avoided. We should use CrudRepository or PagingAndSortingRepository depending on whether you need sorting and paging or not.


2 Answers

Use default Java 8 feature for wrapping, just like so:

// use findOneByEmail instead User findOneByDeletedIsFalseAndEmail(String email);  default User findOneByEmail(String email) {     return findOneByDeletedIsFalseAndEmail(email); } 

See an example.

like image 107
Maksim Kostromin Avatar answered Sep 29 '22 00:09

Maksim Kostromin


Now you can use Java 8 default interface methods as @Maksim Kostromin described. But there is no such a feature in Spring.

-- Old answer

There is no such a way. You can specify any name for a method and add an annotation @Query with parameter value which holds desired query to database like this:

@Query(value="select u from User u where u.deleted=false and u.email=:email") User findOneByEmail(@Param("email")String email); 

or, with native sql query:

@Query(value="SELECT * FROM users WHERE deleted=false AND email=?1", nativeQuery=true) User findOneByEmail(String email); 

You can also use names that follow the naming convention for queries since @Query annotation will take precedence over query from method name.

@Query docs

Upd:

from Spring docs:

Although getting a query derived from the method name is quite convenient, one might face the situation in which ... the method name would get unnecessarily ugly. So you can either use JPA named queries through a naming convention ... or rather annotate your query method with @Query.

like image 30
Lia Avatar answered Sep 29 '22 00:09

Lia