Using Spring-data-MongoDb. In the scenario where we have the following documents
使用Spring-data-MongoDb。在我们有以下文件的情况下
@Document
public class Company {
.
.
@DBRef
List<Person> personnel;
}
And the Person class.
而Person类。
@Document
public class Person {
@Id
public String id;
public String name;
.
.
}
Now if I have saved some persons in the mongodb with ids say 100 and 200, what is the best way save a company with those persons?
现在,如果我拯救了mongodb中的一些人,ids说100和200,那么与这些人一起拯救公司的最佳方式是什么?
1 个解决方案
#1
2
You first create a repository using for instance a MongoRepository interface. Which you autowire to some component/your application.
首先使用MongoRepository接口创建存储库。您自动连接到某个组件/您的应用程序。
Then you can create and save objects to the db as you see fit. You just create the pojo with the nested person pojos and call save.
然后,您可以根据需要创建对象并将其保存到数据库。你只需用嵌套的人pojos创建pojo并调用save。
Note that the persons need to have an ID set and should exist in the database. Keep in mind there is no cascading when you use @Dbref in mongodb!
请注意,人员需要设置ID并且应该存在于数据库中。请记住,在mongodb中使用@Dbref时没有级联!
public interface CompanyRepository extends MongoRepository<Company,String>
{
}
...
@Autowired
CompanyRepository repository
public void createCompany(String name, List<Person> persons)
{
Company company = new Company();
company.setName(name);
company.setPersonnel(persons);
repository.save(company);
}
#1
2
You first create a repository using for instance a MongoRepository interface. Which you autowire to some component/your application.
首先使用MongoRepository接口创建存储库。您自动连接到某个组件/您的应用程序。
Then you can create and save objects to the db as you see fit. You just create the pojo with the nested person pojos and call save.
然后,您可以根据需要创建对象并将其保存到数据库。你只需用嵌套的人pojos创建pojo并调用save。
Note that the persons need to have an ID set and should exist in the database. Keep in mind there is no cascading when you use @Dbref in mongodb!
请注意,人员需要设置ID并且应该存在于数据库中。请记住,在mongodb中使用@Dbref时没有级联!
public interface CompanyRepository extends MongoRepository<Company,String>
{
}
...
@Autowired
CompanyRepository repository
public void createCompany(String name, List<Person> persons)
{
Company company = new Company();
company.setName(name);
company.setPersonnel(persons);
repository.save(company);
}