Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save document with dbref in mongodb spring-data

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?

like image 414
Keyhan Avatar asked Mar 13 '26 15:03

Keyhan


1 Answers

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);
}
like image 157
p.streef Avatar answered Mar 15 '26 05:03

p.streef



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!