/** * 查詢還沒生成索引的帖子 * @return */ @Query(value = "SELECT * FROM t_article WHERE index_state=0",nativeQuery = true) public List<Article> getArticleNoIndex ...
/** * 查詢還沒生成索引的帖子 * @return */ @Query(value = "SELECT * FROM t_article WHERE index_state=0",nativeQuery = true) public List<Article> getArticleNoIndex(); /** * 更改索引為true */ @Transactional @Modifying @Query(value = "UPDATE t_article SET index_state = TRUE WHERE id =?1",nativeQuery = true) public void updateArticleIndex(Integer id);
簡單例子:
@Query(value = "select name,author,price from Book b where b.price>?1 and b.price<?2") List<Book> findByPriceRange(long price1, long price2);
Like表達式:
@Query(value = "select name,author,price from Book b where b.name like %:name%")
List<Book> findByNameMatch(@Param("name") String name);
使用Native SQL Query(nativeQuery=true則使用原生SQL預設HQL)[/b][/color][/size]
所謂本地查詢,就是使用原生的sql語句(根據資料庫的不同,在sql的語法或結構方面可能有所區別)進行查詢資料庫的操作
@Query(value = "select * from book b where b.name=?1", nativeQuery = true) List<Book> findByName(String name);
使用@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);
SPEL表達式(使用時請參考最後的補充說明)[/b]
'#{#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); }
註:
1)update或delete時必須使用@Modifying和@Transactional對方法進行註解,才能使得ORM知道現在要執行的是寫操作
2)有時候不加@Param註解參數,可能會報如下異常:
org.springframework.dao.InvalidDataAccessApiUsageException: Name must not be null or empty!; nested exception is java.lang.IllegalArgumentException: Name must not be null or empty!
3)當使用集合作為條件時,可參考此處的ids
@Transactional
@Modifying
@Query("update ShopCoupon sc set sc.deleted = true where sc.id in :ids")
public void deleteByIds(@Param(value = "ids") List<String> ids);
摘自其他文章,如有侵權,請立即聯繫我