比如有個實體類對象,類名為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