我正在使用spring-boot-starter-data-mongodb构建一个简单的REST api,但是在尝试插入第二行时,总是会出现E11000重复键错误。
Spring的入门指南有一个非常简单的配置,我按照它来做,但我肯定漏掉了什么。
我已经删除了集合并重新开始,第一个文档保存得很好,但第二个文档也试图保存为id=0。如何让Spring/Mongo正确递增?
这是我收到的错误:
游戏仓库
感谢查看!
Spring的入门指南有一个非常简单的配置,我按照它来做,但我肯定漏掉了什么。
我已经删除了集合并重新开始,第一个文档保存得很好,但第二个文档也试图保存为id=0。如何让Spring/Mongo正确递增?
这是我收到的错误:
org.springframework.dao.DuplicateKeyException: { "serverUsed" : "localhost:27017" , "ok" : 1 , "n" : 0 , "err" : "E11000 duplicate key error index: test.game.$_id_ dup key: { : 0 }" , "code" : 11000}; nested exception is com.mongodb.MongoException$DuplicateKey: { "serverUsed" : "localhost:27017" , "ok" : 1 , "n" : 0 , "err" : "E11000 duplicate key error index: test.game.$_id_ dup key: { : 0 }" , "code" : 11000}
Game
package com.recursivechaos.boredgames.domain;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document
public class Game {
@Id
private long id;
private String title;
private String description;
public Game() {
}
public long getId() {
return id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
package com.recursivechaos.boredgames.repository;
import com.recursivechaos.boredgames.domain.Game;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.repository.query.Param;
import java.util.List;
public interface GameRepository extends MongoRepository<Game, Long> {
List<Game> findByTitle(@Param("title") String title);
}
应用程序配置
package com.recursivechaos.boredgames.configuration;
import com.mongodb.Mongo;
import org.springframework.context.annotation.Bean;
import org.springframework.data.authentication.UserCredentials;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
public class AppConfig {
public
@Bean
MongoDbFactory mongoDbFactory() throws Exception {
UserCredentials userCredentials = new UserCredentials("username", "password");
SimpleMongoDbFactory boredgamesdb = new SimpleMongoDbFactory(new Mongo(), "boredgamesdb", userCredentials);
return boredgamesdb;
}
public
@Bean
MongoTemplate mongoTemplate() throws Exception {
return new MongoTemplate(mongoDbFactory());
}
}