1

I want to test a non-transactional method in the service layer when inner methods are transactional separately. I want to know what will happen if some method throws an exception. Does it properly roll back or not? I also tried rollbackFor but it did not help. Any suggestions?

  • Spring v-2.5.1

app.properties

spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root

spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.hibernate.ddl-auto=create-drop

server.error.include-message=always
server.error.include-binding-errors=always

Controller

@PostMapping("/test")
    public void test(){
        service.test();
    }

Service

@Service
public class UserService {
  @Autowired
    private UserRepository userRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;


    public void test() {
        User user1 = new User();
        String encodedPassword = passwordEncoder.encode("123");
        user1.setUsername("username");
        user1.setPassword(encodedPassword);
        user1.setFirst_name("name1");
        user1.setLast_name("family1");
        save(user1);
        User update = update(user1.getUsername());
        throw new RuntimeException();// I expect Spring rollback all data for save and update methods
//but it seems data has been committed before an exception occur.
    }

 @Transactional
    public void save(User user) {
        if (userExists(user.getUsername()))
            throw new ApiRequestException("Username has already taken!");
        else {
            User user1 = new User();
            String encodedPassword = passwordEncoder.encode(user.getPassword());
            user1.setUsername(user.getUsername());
            user1.setPassword(encodedPassword);
            user1.setFirst_name(user.getFirst_name());
            user1.setLast_name(user.getLast_name());
            user1.setCreate_date(user.getCreate_date());
            user1.setModified_date(user.getModified_date());
            user1.setCompany(user.getCompany());
            user1.setAddresses(user.getAddresses());
            userRepository.save(user1);
          //  throw new RuntimeException(); Similarly I expect rollback here.
        }
    }

    @Transactional
    public User update(String username) {
        User userFromDb = userRepository.findByUsername(username);
        userFromDb.setFirst_name("new username");
        userFromDb.setLast_name("new lastname");
        return userRepository.save(userFromDb);
    }

}

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.