我正在使用 spring-boot-starter-data-mongodb 构建一个简单的 REST api,并且E11000 duplicate key error
在尝试插入我的第二行时总是得到一个。
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}
游戏
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());
}
}
感谢您的关注!