spring data jpa @Query註解中delete語句報錯的解決

spring data jpa @Query註解中delete語句報錯

項目中需要刪除掉表中的一些數據

@Query("delete from EngineerServices es where es.engineerId = ?1")
int deleteByEgId(String engineerId);

但是提示瞭錯誤

org.hibernate.hql.QueryExecutionRequestException: Not supported for DML operations

通過查閱相關的資料發現,對於執行update和delete語句需要添加@Modifying註解

@Modifying
@Query("delete from EngineerServices es where es.engineerId = ?1")
int deleteByEgId(String engineerId);

不過,添加之後運行又出現瞭另一個錯誤

nested exception is javax.persistence.TransactionRequiredException: Executing an update/delete query

發現缺少Transaction,於是添加@Transactional

@Modifying
@Transactional
@Query("delete from EngineerServices es where es.engineerId = ?1")
int deleteByEgId(String engineerId);

到此,這條delete語句終於可以成功的執行瞭。

代碼示例:

package com.easy.kotlin.chapter11_kotlin_springboot.dao 
import com.easy.kotlin.chapter11_kotlin_springboot.entity.Image
import org.springframework.data.domain.Page
import org.springframework.data.domain.Pageable
import org.springframework.data.jpa.repository.Modifying
import org.springframework.data.jpa.repository.Query
import org.springframework.data.repository.PagingAndSortingRepository
import org.springframework.data.repository.query.Param
import org.springframework.transaction.annotation.Transactional
 
/** Created by jack on 2017/7/17.
@Query註解裡面的value和nativeQuery=true,意思是使用原生的sql查詢語句.
sql模糊查詢like語法,我們在寫sql的時候是這樣寫的
like '%?%'
但是在@Query的value字符串中, 這樣寫
like %?1%
另外,要註意的是: 對於執行update和delete語句需要添加@Modifying註解
 */
 
interface ImageRepository : PagingAndSortingRepository<Image, Long> {
    @Query("SELECT a from #{#entityName} a where a.isDeleted=0 and a.category like %?1%")
    fun findByCategory(category: String): MutableList<Image>
 
    @Query("select count(*) from #{#entityName} a where a.isDeleted=0 and a.url = ?1")
    fun countByUrl(url: String): Int
 
    @Query("SELECT a from #{#entityName} a where a.isDeleted=0 and a.category like %:searchText%")
    fun search(@Param("searchText") searchText: String, pageable: Pageable): Page<Image>
 
    @Query("SELECT a from #{#entityName} a where a.isDeleted=0 and a.isFavorite=1")
    fun findAllFavorite(pageable: Pageable): Page<Image>
 
    @Query("SELECT a from #{#entityName} a where a.isDeleted=0 and a.isFavorite=1 and a.category like %:searchText%")
    fun searchFavorite(@Param("searchText") searchText: String, pageable: Pageable): Page<Image>
 
    @Modifying
    @Transactional
    @Query("update #{#entityName} a set a.isFavorite=1 where a.id=?1")
    fun addFavorite(id: Long)
 
    @Modifying
    @Transactional
    @Query("delete from #{#entityName} a where a.id=?1")
    fun delete(id: Long) 
} 
 

JPA使用@Query註解實例

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. S模糊查詢註意問題

模糊查詢時在原生sql中like後跟隨的值需要單獨傳,%不支持單獨出現;在使用length查詢數據庫時需要()單獨括起。

@Repository
public interface SaleschargeRespolity extends JpaRepository<Salescharge,Integer> { 
    @Query(value = "select p from Salescharge p where ordertime>:startTime and ordertime<:endTime and staffid like :staffidlike and length(staffid)=(length(:staffid)+2)")    
    List<Salescharge> finAllSubChargeInfo(@Param("startTime") Date startTime, @Param("endTime") Date endTime,@Param("staffid") String staffid, @Param("staffidlike") String staffidlike); 
}

8. 解釋例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);

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: