Search code examples
springhibernatetransactionstransactional

Spring @Transactional usage on wrapper method


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);
}

Solution

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