1

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?

Community
  • 1
  • 1
Gabriel
  • 952
  • 10
  • 31
  • Do you have a UserRepositoryImpl as well - so we can compare the classes? – qtips Apr 17 '17 at 20:23
  • Also add your spring config – qtips Apr 17 '17 at 20:28
  • @qtips The UserRepositoryImpl implements UserRepository. Since there is no custom method on the interface, UserRepositoryImpl is an empty class – Gabriel Apr 18 '17 at 12:03
  • @qtips what configuration do you want to know? I'm using spring boot – Gabriel Apr 18 '17 at 12:05
  • Ah I see. Not an expert, but shouldn't AdressRepositoryImpl be implemententing AddressRepository and not AddressRepositoryCustom? – qtips Apr 18 '17 at 12:10
  • @qtips No... Take a look at the documentation https://docs.spring.io/spring-data/data-commons/docs/1.6.1.RELEASE/reference/html/repositories.html – Gabriel Apr 18 '17 at 12:17

0 Answers0