Spring数据和MongoDB双向连接文档



我有两个文档在我的Spring数据- MongoDB应用程序:第一个是Contact,看起来像这样:

public class Contact {
   ...
   private List<Account> accounts;

第二个是Account,看起来像这样:

public class Account {
    ...
    private Contact contact;

我现在的问题是,是否有更好的方法:

1. create contact object
2. save contact object into database
3. create account object
4. set contact object into account object
5. save account object into database
6. set created account object into contact object
7. update contact object

这是很多步骤,我将避免做这么长的列表来获得联系人和帐户双向连接。

试试这个方法

MongoDB是一个NOSQL数据库,因此不需要保持顺序,比如创建和存储联系人对象,然后以顺序的方式做更多的事情。

维护Contact和Account对象的顺序。在存储这两条记录之前,获取序列中的下一个数字,并插入Contact和Account文档。

自动递增序列的引用

https://docs.mongodb.com/v3.0/tutorial/create-an-auto-incrementing-field/https://www.tutorialspoint.com/mongodb/mongodb_autoincrement_sequence.htm

伪代码:

Get the next Sequence of Contact and Account Id
Add the id's to respective documents
Insert the Documents in Mongodb

当检索记录时,你可以使用$lookup,这是一个左外连接。

请注意,如果一次插入成功,而其他插入由于某种原因没有发生,则可能发生数据完整性丢失的可能性。我们在Mongodb中不支持跨集合的事务,更多信息

最新更新