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
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.
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.
You forgot to add two annotations
above of method .
@Transactional
@Modifying
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.