本文共 2552 字,大约阅读时间需要 8 分钟。
项目中需要删除掉表中的一些数据
@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.daoimport com.easy.kotlin.chapter11_kotlin_springboot.entity.Imageimport org.springframework.data.domain.Pageimport org.springframework.data.domain.Pageableimport org.springframework.data.jpa.repository.Modifyingimport org.springframework.data.jpa.repository.Queryimport org.springframework.data.repository.PagingAndSortingRepositoryimport org.springframework.data.repository.query.Paramimport 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{ @Query("SELECT a from #{#entityName} a where a.isDeleted=0 and a.category like %?1%") fun findByCategory(category: String): MutableList @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 @Query("SELECT a from #{#entityName} a where a.isDeleted=0 and a.isFavorite=1") fun findAllFavorite(pageable: Pageable): Page @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 @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)}
转载地址:http://gljyo.baihongyu.com/