Using Spring-data-MongoDb. In the scenario where we have the following documents
@Document
public class Company {
.
.
@DBRef
List<Person> personnel;
}
And the Person class.
@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?
You first create a repository using for instance a MongoRepository interface. Which you autowire to some component/your application.
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.
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!
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With