JpaRepository Not supported for DML operations [delete query]

前端 未结 4 390
南笙
南笙 2020-12-13 05:39

I have written a query to delete some objects in my interface extending JPaRepository, but when I execute the query it throws an exception! Can anyone explain

相关标签:
4条回答
  • 2020-12-13 05:50

    Try this:

    public interface LimitRepository extends JpaRepository<CLimit, Long> {
    
      @Transactional
      @Modifying
      @Query("delete from CLimit l where l.trader.id =:#{#trader.id}")
      void deleteLimitsByTrader(@Param("trader") CTrader trader);
    
    }
    

    Whenever you are trying to modify a record in db, you have to mark it @Transactional as well as @Modifying, which instruct Spring that it can modify existing records.
    The repository method must be void or the exception keeps getting thrown.

    0 讨论(0)
  • 2020-12-13 05:55

    I had the same issue and I tried @afridi's answer which is working fine but bad practice, as far as I understand. you should not use @Transactional annotation in the repository class but service(and implementation) classes. please find the below answer.

    LimitServiceImpl.java

    import org.springframework.transaction.annotation.Transactional;
    ...
    @Override
    @Transactional
    public void deleteLimitsByTrader(CTrader trader) {
    // here im calling the LimitRepository interface. 
     getEntityRepository().deleteLimitsByTrader(trader);
    }
    

    LimitRepository.java

    import org.springframework.data.jpa.repository.Modifying;
    import org.springframework.data.jpa.repository.Query;
    ...
    public interface LimitRepository extends JpaRepository<CLimit, Long> {
    
      @Modifying
      @Query("delete from CLimit l where l.trader.id =:#{#trader.id}")
      void deleteLimitsByTrader(@Param("trader") CTrader trader);
    
    }
    

    make sure to use the correct imports.

    0 讨论(0)
  • 2020-12-13 06:09

    You forgot to add two annotations above of method .

    @Transactional
    @Modifying
    
    0 讨论(0)
  • 2020-12-13 06:13

    I solved the issue by using EntityManager.createQuery("your deleteStatement").executeUpdate();

    I Understand the question is already answered but still posting it, might be useful to other in need of solution.

    0 讨论(0)
提交回复
热议问题