调用另一个没有@Transactional注释的方法的@Transactional方法适用于保存,但不适用于更新

时间:2017-04-17 19:52:09

标签: java spring transactions

我之前知道这个问题是asked,但我仍然无法理解以下代码的错误:

@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public void doStuff(User user, Address address) {
    userService.save(user);
    addressService.update(address);
}

使用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();
}

}

基于answer,&#34;当您在事务块中调用没有@Transactional的方法时,父事务将继续使用新方法&#34;。这实际上适用于save方法。但是,在update方法上,抛出以下异常:

javax.persistence.TransactionRequiredException:执行更新/删除查询

我想知道为什么会这样,解释是什么?

0 个答案:

没有答案