1. 程式人生 > >@Query註解的用法(Spring Data JPA)

@Query註解的用法(Spring Data JPA)

1. 一個使用@Query註解的簡單例子

@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表示式

@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}'值為'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);

}

6. 一個較完整的例子

複製程式碼

public interface BookQueryRepositoryExample extends Repository<Book, Long> {
    @Query(value = "select * from Book b where b.name=?1", nativeQuery = true) 
    List<Book> findByName(String name);// 此方法sql將會報錯(java.lang.IllegalArgumentException),看出原因了嗎,若沒看出來,請看下一個例子

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

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

    @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);

}

複製程式碼

7.  解釋例6中錯誤的原因:

     因為指定了nativeQuery = true,即使用原生的sql語句查詢。使用java物件'Book'作為表名來查自然是不對的。只需將Book替換為表名book。

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

補充說明(2017-01-12):

  有同學提出來了,例子5中用'#{#entityName}'為啥取不到值啊?

  先來說一說'#{#entityName}'到底是個啥。從字面來看,'#{#entityName}'不就是實體類的名稱麼,對,他就是。

  實體類Book,使用@Entity註解後,spring會將實體類Book納入管理。預設'#{#entityName}'的值就是'Book'。

  但是如果使用了@Entity(name = "book")來註解實體類Book,此時'#{#entityName}'的值就變成了'book'。

  到此,事情就明瞭了,只需要在用@Entity來註解實體類時指定name為此實體類對應的表名。在原生sql語句中,就可以把'#{#entityName}'來作為資料表名使用。