0

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);
}
yons88
  • 439
  • 2
  • 5
  • 20

4 Answers4

2

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).

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
1

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

Manoj Kathiriya
  • 3,366
  • 5
  • 19
  • 19
0

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.

Jayamohan
  • 12,734
  • 2
  • 27
  • 41
0

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)

gerrytan
  • 40,313
  • 9
  • 84
  • 99