publicinterfaceUserRepositoryextendsJpaRepository<User,Long> { @Query("select u from User u where u.emailAddress = ?1")UserfindByEmailAddress(String emailAddress);}
publicinterfaceUserRepositoryextendsJpaRepository<User,Long> { @Query("select u from User u where u.firstname like %?1")List<User> findByFirstnameEndsWith(String firstname);}
如果你不会使用 JPQL 查询,也可以使用 SQL 查询,也即使用 Native Query:
publicinterfaceUserRepositoryextendsJpaRepository<User,Long> { @Query(value ="SELECT * FROM USERS WHERE EMAIL_ADDRESS = ?1", nativeQuery =true)UserfindByEmailAddress(String emailAddress);}
Spring Data JPA does not currently support dynamic sorting for native queries, because it would have to manipulate the actual query declared, which it cannot do reliably for native SQL. You can, however, use native queries for pagination by specifying the count query yourself, as shown in the following example:
publicinterfaceUserRepositoryextendsJpaRepository<User,Long> { @Query(value ="SELECT * FROM USERS WHERE LASTNAME = ?1", countQuery ="SELECT count(*) FROM USERS WHERE LASTNAME = ?1", nativeQuery =true)Page<User> findByLastname(String lastname,Pageable pageable);}
Modifying
The @Modifying annotation is used to enhance the @Query annotation so that we can execute not only SELECT queries, but also INSERT, UPDATE, DELETE, and even DDL queries.
@Modifying@Query("update User u set u.active = false where u.lastLoginDate < :date")voiddeactivateUsersNotLoggedInSince(@Param("date") LocalDate date);
@Modifying@Query("delete User u where u.active = false")intdeleteDeactivatedUsers();