jpa自定義sql語句

 /**
     * 查詢還沒生成索引的帖子
     * @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);

簡單例子:java

@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表達式:spring

@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的語法或結構方面可能有所區別)進行查詢數據庫的操做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)。spa

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

}

 

注:code

1)update或delete時必須使用@Modifying和@Transactional對方法進行註解,才能使得ORM知道如今要執行的是寫操做對象

2)有時候不加@Param註解參數,可能會報以下異常:blog

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)當使用集合做爲條件時,可參考此處的idsget

@Transactional
@Modifying
@Query("update ShopCoupon sc set sc.deleted = true where sc.id in :ids")
public void deleteByIds(@Param(value = "ids") List<String> ids);

 

摘自其餘文章,若有侵權,請當即聯繫我

相關文章
相關標籤/搜索