Java 在mongodb spring数据中使用dbref保存文档
使用Spring数据MongoDb。 在我们有以下文档的场景中Java 在mongodb spring数据中使用dbref保存文档,java,spring,mongodb,spring-data-mongodb,Java,Spring,Mongodb,Spring Data Mongodb,使用Spring数据MongoDb。 在我们有以下文档的场景中 @Document public class Company { . . @DBRef List<Person> personnel; } 现在,如果我在mongodb中保存了一些ID为100和200的人员,那么用这些人员保存公司的最佳方法是什么?首先使用MongoRepository接口创建存储库。将其自动连接到某个组件/应用程序 然后,您可以根据需要创建对象并将其保存到数据库中。您只需使用嵌套的personpojo
@Document
public class Company {
.
.
@DBRef
List<Person> personnel;
}
现在,如果我在mongodb中保存了一些ID为100和200的人员,那么用这些人员保存公司的最佳方法是什么?首先使用MongoRepository接口创建存储库。将其自动连接到某个组件/应用程序 然后,您可以根据需要创建对象并将其保存到数据库中。您只需使用嵌套的personpojo创建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);
}
public interface CompanyRepository扩展了MongoRepository
{
}
...
@自动连线
公司存储库
公共公司(字符串名称、人员列表)
{
公司=新公司();
公司名称(名称);
公司人员(人);
保存(公司);
}
使用惰性
@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;
.
.
}
@文档
公营公司{
.
.
@DBRef(lazy=true)
列出人员名单;
}
还有Person类。
@文件
公共阶层人士{
@身份证
公共字符串id;
公共字符串名称;
.
.
}
在这种情况下,您似乎需要RDB。是否可以跳过让该人员全部加入公司?我的意思是只使用个人id。据我所知,DBRef是指MongoDB中指向另一个文档的链接,因此,既然此人已经存在于db中,那么只需给它id就足够了,它应该链接到它,还是我错了?您是对的,在本例中也可以这样做。Afaik只有@Id字段必须亲自设置才能执行此操作。因此,如果您只是创建一个“空”人,并将id设置为100/200,那么工作集应该稍等片刻,看看是否有人有更好的解决方案,否则我将接受您的答案作为正确答案。更好的方法是用Java完全管理它。由于您已将这些人员保存到数据库中,因此您的内存中已经有了这些人员,如果没有,您可以重新加载(从数据库中),您将以某种方式将这些人员添加到公司中(可能有一些前端),并显示这些用户。所以你应该把实际的用户对象添加到公司并保存它。。。但是当你问是否有可能仅仅用这个想法。答案是肯定的。。
@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;
.
.
}