天天看點

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

版權聲明:本文為部落客原創文章,未經部落客允許不得轉載。 https://blog.csdn.net/qq_34173549/article/details/81666533

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

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

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

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

@Transactional

到此,這條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)
 
}