Spring Data JPA之@Query注解

比如有个实体类对象,类名为Book,对应数据表的表名为book 

1. 一个使用@Query注解的简单例子:占位符?1?2

@Query(value = "select name,author,price from Book b where b.price>?1 and b.price<?2")
List<Book> findByPriceRange(long price1, long price2);

 

2.  Like表达式:指定参数 :name,下面要用@Param("name")指明对应的参数

@Query(value = "select name,author,price from Book b where b.name like %:name%")
List<Book> findByNameMatch(@Param("name") String name);

 

3. 使用Native SQL Query

所谓本地查询,就是使用原生的sql语句,直接查询数据表名,而不是实体类对象(根据数据库的不同,在sql的语法或结构方面可能有所区别)进行查询数据库的操作。

@Query(value = "select * from book b where b.name=?1", nativeQuery = true)
List<Book> findByName(String name);

 

4. 使用@Param注解注入参数

@Query(value = "select name,author,price from Book b where b.name = :name AND b.author=:author AND b.price=:price")
List<Book> findByNamedParam(@Param("name") String name, @Param("author") String author,@Param("price") long price);

 

5. SPEL表达式( 特别说明:本条可能有误,待验证,不使用#{#entityName},直接使用表名是ok的 )

   此处的 '#{#entityName}'值为'Book'对象对应的数据表名称(book)。

public interface BookQueryRepositoryExample extends Repository<Book, Long>{

       @Query(value = "select * from #{#entityName} b where b.name=?1", nativeQuery = true)
       List<Book> findByName(String name);

}

 

参考:

http://www.cnblogs.com/zj0208/p/6008627.html

原文地址:https://www.cnblogs.com/Donnnnnn/p/6275355.html