Dev/Spring

[JPA] cannot reliably process 'remove' call 오류(에러)해결

Mr.Walker 2023. 2. 9. 14:32
반응형

JPA로 테이블에 저장한 로우를 삭제하려고 했으나 다음과 같은 오류(에러)가 발생했다.

* 오류(에러)메시지

No EntityManager with actual transaction available for current thread - cannot reliably process 'remove' call; nested exception is javax.persistence.TransactionRequiredException: No EntityManager with actual transaction available for current thread - cannot reliably process 'remove' call

* 소스코드

public void function() {
// 소스코드 중략...
repository.saveAll(saveList);
repository.deleteByColumn1AndColumn2(Integer c1, Integer c2);
// 이하 생략
}

SimpleJpaRepository에서는 몇 가지의 delete에 대해 트랜잭션을 제공한다.

! 시간 날 때 해당 클래스를 찾아서 직접 보는 것도 도움이 되니 확인하면 좋다.

! ClassName(클래스명) : SimpleJpaRepository.class 

public void delete(T entity)
public void deleteInBatch(Iterable<T> entities)
public void deleteAll()
public void deleteAllInBatch()

 

 

Repository에서 기본적으로 트랜잭션이 붙는 줄 알았지만 deleteBy를 사용하여 직접 조건을 거는 경우에는 트랜젝션을 기본제공하지 않아 수정된 코드와 같이 해당 메서드에 하거나 직접 선언한 Repository에서 커스텀한 delete문에 직접 어노테이션을 붙여주면 된다.

* 수정후 코드

TestService.java
@Transactional
public void function() {
// 소스코드 중략...
repository.saveAll(saveList);
repository.deleteByColumn1AndColumn2(Integer c1, Integer c2);
// 이하 생략
}

Testepository.java
public interface Testepository extends JpaRepository<TestVo, Integer> {
    @Transactional
    void deleteByColumn1AndColumn2(Integer c1, Integer c2);
}

 

반응형