在 mongodb spring-data 中使用 dbref 保存文档

Save document with dbref in mongodb spring-data

使用Spring-数据-MongoDb。 在我们有以下文档的场景中

@Document
public class Company {
.
.
@DBRef
List<Person> personnel;
}

还有那个人 class。

@Document
public class Person {
@Id
public String id;

public String name;
.
.
}

现在,如果我在 mongodb 中保存了 ID 分别为 100 和 200 的一些人,保存这些人的公司的最佳方法是什么?

您首先使用 MongoRepository 接口创建一个存储库。您自动连接到某些 component/your 应用程序。

然后您可以根据需要创建对象并将其保存到数据库中。您只需使用嵌套的人员 pojo 创建 pojo 并调用保存。

请注意,这些人需要有一个 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);
}

使用延迟

@Document
public class Company {
.
.
@DBRef(lazy=true)
List<Person> personnel;
}
And the Person class.

@Document
public class Person {
@Id
public String id;

public String name;
.
.
}