Open ythy opened 5 years ago
public interface UserRepository extends JpaRepository<User, Long> {
@Query("select u from User u where u.lastname like ?1%")
List<User> findByAndSort(String lastname, Sort sort);
@Query("select u.id, LENGTH(u.firstname) as fn_len from User u where u.lastname like ?1%")
List<Object[]> findByAsArrayAndSort(String lastname, Sort sort);
}
1. repo.findByAndSort("lannister", new Sort("firstname"));
2. repo.findByAndSort("stark", new Sort("LENGTH(firstname)"));
3. repo.findByAndSort("targaryen", JpaSort.unsafe("LENGTH(firstname)"));
4. repo.findByAsArrayAndSort("bolton", new Sort("fn_len"));
By default, Spring Data JPA uses position-based parameter binding, as described in all the preceding examples. This makes query methods a little error-prone when refactoring regarding the parameter position. To solve this issue, you can use @Param annotation to give a method parameter a concrete name and bind the name in the query, as shown in the following example:
public interface UserRepository extends JpaRepository<User, Long> {
@Query("select u from User u where u.firstname = :firstname or u.lastname = :lastname")
User findByLastnameOrFirstname(@Param("lastname") String lastname,
@Param("firstname") String firstname);
}
reference
Query Lookup Strategies
The JPA module supports defining a query manually as a String or having it being derived from the method name
Declared Queries
Although getting a query derived from the method name is quite convenient, one might face the situation in which either the method name parser does not support the keyword one wants to use or 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
Query Creation
We create a query using the JPA criteria API from this, but, essentially, this translates into the following query:
select u from User u where u.emailAddress = ?1 and u.lastname = ?2
Supported keywords inside method names: