Pergunta

Do I need to add @Transactional annotation to second method? I think not, but really not sure.

@Transactional
public void addUser(User u) {
    u.setCreationDate(new Date());
    userDAO.addUser(u);
}

// should I add @Transactional annotation here?
public User addUser(String name, String surname) {
    User user = new User();
    user.setName(name);
    user.setSurname(surname);
    this.addUser(user);
    return user;
}

// DAO method
public void addUser(User u) {
    entityManager.persist(u);
}
Foi útil?

Solução

You need to add the @Transactional annotation to the public User addUser(String name, String surname) method other wise the method will execute in a non transactional way.

@Transactional uses proxy mechanism to implement transactional support, it will be invoked only when you call the method from a second object (ie If you call a method within the same class it will not go through the proxy system so it will always run using the callers transaction).

Outras dicas

Both are different method as signature is diff, hence needs to add @Transactional annotation. As you knows spring is working on proxy object

You don't need to annotate the wrapper methods if you are using default @Transactional settings. The PROPAGATION settings in @Transactional defines transactional scope. The default propagation setting is PROPAGATION_REQUIRED.

Refer here for more details.

In your case it will produce similar result. The difference is if you put @Transactional on public User addUser(String name, String surname) you will be creating a new user under context of a transaction. If you don't -- a transaction will only start when your code executes public void addUser(User u)

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top