I know this question has been asked before, but I can't still understand what is wrong with the following code:
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public void doStuff(User user, Address address) {
userService.save(user);
addressService.update(address);
}
Below the following classes using Spring Data
@Service
public class UserService {
public User save(User user) {
return userRepository.save(user);
}
}
-
public interface UserRepository extends JpaRepository<User, Long>, UserRepositoryCustom {
}
-
@Service
public class AddressService {
public Address update(Address address) {
return addressRepository.update(address);
}
}
-
public interface AddressRepository extends JpaRepository<Address, Long>, AddressRepositoryCustom {
}
-
public interface AddressRepositoryCustom {
void update(Address address);
}
-
@Repository
public class AddressRepositoryImpl implements AddressRepositoryCustom {
@PersistenceContext
private EntityManager entityManager;
private JPAQueryFactory query;
@PostConstruct
public void setUp(){
query = new JPAQueryFactory(entityManager);
}
@Override
public void update(Address entity) {
QAddress qAddress = QAddress.address;
JPAUpdateClause update = new JPAUpdateClause(entityManager, qAddress);
update.where(qAddress.id.eq(entity.getId())).set(qAddress.number,entity.getNumber()).execute();
}
}
Based on the answer, "When you call a method without @Transactional within a transaction block, the parent transaction will continue to the new method". This actually works with the save method. However, on the update method, the following exception is thrown:
javax.persistence.TransactionRequiredException: Executing an update/delete query
I want to know why this happens, what is the explanation?