Spring MongoRepository entity saved twice

时间:2018-03-25 19:02:35

标签: java mongodb spring-boot spring-data-mongodb

I Have method in service to save user after registration, but after method invocation I have two same documents in collection.

Controller:

    @RequestMapping(value="/registration/male", method= RequestMethod.POST, consumes={ MediaType.APPLICATION_JSON_VALUE })
    public @ResponseBody void maleRegistration (@RequestBody MaleDTO maleDTO, HttpServletRequest request) throws EmailExistsException {
        User user = registrationService.maleRegistration(maleDTO);
        autoLogin(user, request);
    }

Method in service:

@Transactional
public User maleRegistration(MaleDTO male) throws EmailExistsException {
    if (userRepository.existsByEmail(male.getEmail())) {
        throw new EmailExistsException("There is an account with that email address: " + male.getEmail());
    }
    User user = new User();
    user.setName(male.getName());
    user.setGender(Gender.MALE);
    user.setDateOfBirth(male.getDateOfBirth());
    user.setEmail(male.getEmail());
    user.setPassword(encoder.encode(male.getPassword()));
    user.setRoles(new HashSet<>(Arrays.asList(Role.ROLE_USER)));

    userRepository.save(user);

    return user;
}

User repository:

   public interface UserRepository extends MongoRepository<User, String>{
}

User Class:

@Document(collection = "Users")
public class User {
    @Id
    private String id;
    private String name;
    private Gender gender;
    private LocalDate dateOfBirth;
    private String email;
    private String password;
    private Set<Role> roles;
   //geters and seters
   //toString
}

Why it happens? I would appreciate any help.

0 个答案:

没有答案