簡體   English   中英

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

[英]Save document with dbref in mongodb spring-data

使用 Spring-data-MongoDb。 在我們有以下文件的場景中

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

和 Person 類。

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

public String name;
.
.
}

現在,如果我在 mongodb 中拯救了一些 id 為 100 和 200 的人,那么與這些人一起拯救公司的最佳方法是什么?

您首先使用例如 MongoRepository 接口創建存儲庫。 您自動連接到某個組件/您的應用程序。

然后,您可以根據需要創建對象並將其保存到數據庫中。 您只需使用嵌套的 person pojo 創建 pojo 並調用 save。

請注意,這些人需要有一個 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;
.
.
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM