如何在 Spring Data 中将 Java 实体映射到多个 MongoDB 集合? [英] How to Map a Java Entity to Multiple MongoDB Collections in Spring Data?
问题描述
目前,我们正在寻找一种解决方案,将以下 User
实体同时保存到多个 MongoDB 集合中(即 db_users
和 db_users_legacy代码>).两个集合都在同一个数据库中.
Currently, we're looking for a solution to save the following User
entity into multiple MongoDB collections at the same time (i.e. db_users
and on db_users_legacy
). Both collections are in the same database.
请不要问我为什么需要保存在两个集合中.这是业务需求.
Please don't ask me the reason why I need to save in two collections. It is a business requirement.
@Document(collection = "db_users")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
@Id
private String id;
private String name;
private String website;
private String name;
private String email;
}
我的 SpringBoot 应用程序配置如下;
And my SpringBoot application configuration goes as;
@Configuration
public class ApplicationConfig {
@Bean
public MongoTemplate mongoTemplate(MongoDbFactory factory){
MongoTemplate template = new MongoTemplate(factory);
template.setWriteConcern(WriteConcern.ACKNOWLEDGED);
retu,rn template;
}
}
目前我的存储库看起来像这样.并且保存工作得很好.如何在两个不同的集合中相同此文档?
Currently my repository looks as this. And saving works perfectly fine. How can I same this document in two different collections?
@Repository
public class UserRepositoryImpl implements UserRepository {
private MongoTemplate mongoTemplate;
public UserRepositoryImpl(MongoTemplate mongoTemplate) {
this.mongoTemplate = mongoTemplate;
}
@Override
public void save(User user) {
mongoTemplate.save(user);
}
}
有人可以建议最好的选择来解决这个问题吗?
Can anyone suggest the best option to deal with this, please?
推荐答案
我建议使用 MongoTemplate
的另一个 重载保存方法一>.
I suggest using MongoTemplate
's the other overloaded save method.
@Override
public void save(User user) {
mongoTemplate.save(user, "db_users");
mongoTemplate.save(user, "db_users_legacy");
}
这可用于将同一对象保存到多个集合中.来自文档,
This can be used to save same object to multiple collections. From docs,
您可以通过使用 @Document 批注提供不同的集合名称来自定义它.您还可以通过提供您自己的集合名称作为所选 MongoTemplate 方法调用的最后一个参数来覆盖集合名称.
You can customize this by providing a different collection name using the @Document annotation. You can also override the collection name by providing your own collection name as the last parameter for the selected MongoTemplate method calls.
因此,@Document
中专门提供的集合名称无关紧要,您始终可以使用 MongoTemplate
覆盖它.
So it doesn't matter the collection name specifically provided in @Document
, you can always override it using MongoTemplate
.
这篇关于如何在 Spring Data 中将 Java 实体映射到多个 MongoDB 集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!