[英]Spring Boot findById not working for MongoDB
I'm trying to do a simple get query on springboot using mongodb as database engine我正在尝试使用 mongodb 作为数据库引擎对 springboot 进行简单的获取查询
I have tried with several stuff(sending the data as ObjectId and even changing the repository)我尝试了几种方法(将数据作为 ObjectId 发送,甚至更改存储库)
public ResponseEntity<Track> get(String trackId) {
Track find = mongoTemplate.findById(new ObjectId(trackId), Track.class);
Optional<Track> track = tracksRepository.findById(trackId);
if (track.isPresent()) {
return new ResponseEntity<>(track.get(), HttpStatus.OK);
}
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
with mongo config使用 mongo 配置
@Configuration
@EnableMongoRepositories(basePackages = "data.store.repositories")
public class MongoConfig extends AbstractMongoClientConfiguration {
private final Logger LOGGER = Logger.getLogger(this.getClass().getSimpleName());
@Primary
@Bean
@Override
public MongoClient mongoClient() {
return MongoClients.create(MongoClientSettings.builder()
.applyToClusterSettings(builder -> builder.hosts(Arrays.asList(new ServerAddress(host, port))))
.build());
}
private MongoCredential mongoCredentials() {
return MongoCredential.createCredential(username, database, password.toCharArray());
}
@Bean
public MongoTemplate mongoTemplate() {
MongoTemplate mongoTemplate = new MongoTemplate(mongoClient(), getDatabaseName());
mongoTemplate.setReadPreference(ReadPreference.secondaryPreferred());
return mongoTemplate;
}
protected String getDatabaseName() {
return database;
}
@Override
public boolean autoIndexCreation() {
return false;
}
}
EDIT: Adding class for context编辑:为上下文添加 class
@Document("track")
public class Track {
@Id
@Field(ATTR_ID)
@JsonProperty(ATTR_ID)
public String id;
public static final String ATTR_ID = "id";
}
and getting always null, with existing keys on my database.并始终使用我数据库中的现有密钥获取 null。 could you help me find the issue?你能帮我找到问题吗?
Thanks in advance提前致谢
I tried this with similar configuration class and found the following worked fine creating/accessing data using MongoTemplate
.我用类似的配置 class 尝试了这个,发现以下使用MongoTemplate
创建/访问数据的工作正常。
The POJO class: POJO class:
public class Test {
@MongoId(FieldType.OBJECT_ID)
private String id;
private String name;
public Test() {
}
public Test(String s) {
super();
this.name = s;
}
// get, set methods
public String toString( ) {
return id + " - " + name;
}
}
From Spring's CommandLineRunner.run()
:从 Spring 的CommandLineRunner.run()
:
// Insert a document into the database
Test t1 = new Test("alpha");
t1 = mt.insert(t1);
System.out.println(t1); // 61e7de9f5aadc2077d9f4a58 - alpha
// Query from the database using the _id
ObjectId id = new ObjectId("61e7de9f5aadc2077d9f4a58");
Test t2 = mt.findById(id, Test.class);
System.out.println(t2);
Note that you need to do this from the class where you are running the code:请注意,您需要从运行代码的 class 执行此操作:
@Autowired private MongoTemplate mt;
You can use the @MongoId
or @Id
annotations in our POJO class to represent MongoDB _id
field.您可以在我们的 POJO class 中使用@MongoId
或@Id
注释来表示 MongoDB _id
字段。 The type of the field can be a String
or ObjectId
.字段的类型可以是String
或ObjectId
。 It depends upon how you define.这取决于你如何定义。
See this from Spring Data MongoDB documentation on How the _id Field is Handled in the Mapping Layer using:请参阅 Spring 数据 MongoDB 文档中有关如何在映射层中处理 _id 字段的文档,使用:
Solution is to add to MongoId annotation field type object id解决方案是添加到 MongoId 注释字段类型 object id
@MongoId(FieldType.OBJECT_ID)
private String id;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.