mongodb和spring boot中的DuplicateKeyException

时间:2018-05-24 12:20:45

标签: spring mongodb spring-boot spring-data

我正在使用Spring Boot和MongoDB,我能够成功地在MongoDB中存储文档。当我尝试插入第二个文档时,它显示XMLHttpRequest。异常的总消息如下:

  

com.mongodb.DuplicateKeyException:写入失败,错误代码为11000   和错误消息'E11000重复键错误集合:   Football_Admin.SignUp index: id dup key:{:0}'

代码如下:

SignUpRepository.java

duplicatekeyexception

控制器

package com.admin.Repository;

import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;

import com.admin.Model.SignUp;

@Repository
public interface SignUpRepository extends MongoRepository<SignUp,String>{

}

实体

@Controller
@RequestMapping("/SignIn_Up")
public class HomeController {

    @Autowired
    SignUpRepository repository;


    @RequestMapping(value = "/addadmin", method = RequestMethod.POST)
    public String addAdmin(@ModelAttribute("SignUp") SignUp sign) throws NoSuchAlgorithmException,InvalidKeySpecException {
        String  originalPassword = sign.getPassword();
        String generatedSecuredPasswordHash = generateStorngPasswordHash(originalPassword);
        String email = sign.getEmail();
        String fullname = sign.getFullName();
        try {
        sign.setEmail(email);
        sign.setFullName(fullname);
        sign.setPassword(generatedSecuredPasswordHash);
        repository.save(sign);
        }
        catch (DuplicateKeyException e) {
            e.printStackTrace();
        }
        System.out.println(generatedSecuredPasswordHash);
        System.out.println("Email name is:"+sign.getEmail());
        System.out.println("Full Name is:"+sign.getFullName());
        System.out.println("Password is:"+sign.getPassword());
        return "welcome";
    }

1 个答案:

答案 0 :(得分:2)

MongoDb驱动程序在插入时不知道如何创建类型int的唯一ID,因此您收到了唯一索引异常

因此,您手动创建和维护索引(非常难)或将您的ID字段类型更改为ObjectId