Spring Repository Transnationality

Posted by ChenRiang on May 30, 2021

Recently, I met the following exception when trying to create my custom delete method on repository.

org.springframework.dao.InvalidDataAccessApiUsageException: 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

Root Cause

By default Spring only mark the CRUD methods as transactional. Hence, the custom query method we defined does not inherit the transactional annotation.

Solution

Just mark the custom method with @Transactional .

1
2
3
4
5
6
7
8
public interface ComponentDependencyRepository extends JpaRepository<UserProfile, String> {

    List<ComponentDependency> findByPhoneNo(String phoneNo);

    @Transactional
    void deleteByPhoneNo(String phoneNo);

}


Reference

Stackoverflow