'Springboot does not save user properly using JpaRepository

I couldn't use userRepo to saveUser properly, the mysql query showed wrong order of insertion, therefore not working. Here's my UserRepository:

import org.springframework.data.jpa.repository.JpaRepository;


public interface UserRepository extends JpaRepository<User, Integer> {

    Optional<User> findUserByUsername(String username);
}

Here's my user service:

@Service
public class UserServiceImpl implements IUserService, UserDetailsService {
    
    private Logger logger = LogManager.getLogger(UserServiceImpl.class);
    @Autowired
    private UserRepository userRepo;
    
    @Autowired
    private BCryptPasswordEncoder encoder;
    
    //field name not in correct order, can not use it
    @Override
    public Integer saveUser(User user) {
        String passwd = user.getPassword();
        String encodedPasswod = encoder.encode(passwd);
        logger.log(Level.ERROR, "passwd:" + encodedPasswod);
        user.setPassword(encodedPasswod);
        ArrayList<String> roles = new ArrayList<String>();
        roles.add("Member");
        user.setRoles(roles);
        user = userRepo.save(user);
        return user.getUserid();
    }

    public UserServiceImpl(UserRepository userRepository) {
        this.userRepo = userRepository;
    }
    ...

Someone can help? So frustrated with springboot.

M.



Solution 1:[1]

Look like you missing @Transactional on the saveUser method.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Chayne P. S.