1

I want to setup simple rest api app on Spring boot java. I created users table. I created get all users and get one user. And I want to delete user by username.

UsersController.java

@RestController
public class UsersController {
    @Autowired
    private UsersService usersService;

    @DeleteMapping("/users/{username}")
    public void delete(@PathVariable String username) {
        usersService.delete(username);
    }
}

UsersRepository.java

@Repository
public interface UsersRepository extends JpaRepository<User, Long> {

    User findByUsername(String username);
    Long deleteByUsername(String username);

}

I can to delete user by username if I use delete(User user).

UsersService.java

@Service
public class UsersServiceImpl implements UsersService {

    @Autowired
    private UsersRepository usersRepository;

    @Override
    public void delete(String username) {
        User user = usersRepository.findUserByUsername(username);
        usersRepository.delete(user);
    }

But I cannot do it with deleteByUsername. It doesn't work. Why?

@Service
public class UsersServiceImpl implements UsersService {

    @Autowired
    private UsersRepository usersRepository;

    @Override
    public void delete(String username) {
        usersRepository.deleteByUsername(username);
    }

I get errors

javax.persistence.TransactionRequiredException: No EntityManager with actual transaction available for current thread - cannot reliably process 'remove' call
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:295) ~[spring-orm-5.3.6.jar:5.3.6]
at jdk.proxy4/jdk.proxy4.$Proxy82.remove(Unknown Source) ~[na:na]
...
at jdk.proxy4/jdk.proxy4.$Proxy86.deleteByUsername(Unknown Source) ~[na:na]
...

And what is the difference between delete() and remove()?

Oleg B
  • 21
  • 3
  • 2
    Add `@Transactional` to your `UsersServiceImpl` above `@Service` – Chol Nhial Apr 29 '21 at 23:30
  • Thanks! It works. And what is the difference between delete() and remove()? – Oleg B Apr 29 '21 at 23:50
  • 2
    Does this answer your question? [Spring - No EntityManager with actual transaction available for current thread - cannot reliably process 'persist' call](https://stackoverflow.com/questions/32269192/spring-no-entitymanager-with-actual-transaction-available-for-current-thread) – İsmail Y. Apr 29 '21 at 23:54

0 Answers0