spring-mongodb-DBRef的运用

来源:互联网 发布:速卖通数据分析助手 编辑:程序博客网 时间:2024/05/25 18:09


spring-mongodb的框架搭建详情可参考 

java-spring与mongodb的整合方式一 自动注入xml


DBref 是mongodb中的引用,与其它集合的关联。


比如 我有一个学生类  学生类下面有班级类    这里班级 就可以设置成 DBref的 形式。

有一个好处就是 当数据库中的 班级类 数据 变动时,学生类 提取出来的也是变动后的数据。


spring-mongodb中的DBRef使用很简单。

只要在引用的类中 在引用字段上加上标识就可以了。存取都按正常的set  和get

下面看官方代码示例:

Person类

@Document(collection="person")@CompoundIndexes({    @CompoundIndex(name = "age_idx", def = "{'lastName': 1, 'age': -1}")})public class Person<T extends Address> {   @Id  private String id;  @Indexed(unique = true)  private Integer ssn;  private String firstName;  @Indexed  private String lastName;  private Integer age;  @Transient  private Integer accountTotal;  @DBRef  private List<Account> accounts;  private T address;      public Person(Integer ssn) {    this.ssn = ssn;  }  private List<Account> accounts;public List<Account> getAccounts() { return accounts;}public void setAccounts(List<Account> accounts) {this.accounts = accounts;}  @PersistenceConstructor  public Person(Integer ssn, String firstName, String lastName, Integer age, T address) {    this.ssn = ssn;    this.firstName = firstName;    this.lastName = lastName;    this.age = age;    this.address = address;  }
Account类
@Documentpublic class Account {   @Id  private ObjectId id;  private Float total; }....get + set


保存和使用

保存

我们主要到 person类中已经有了 List<Account> accounts的get和set

那我们在保存的地方

 List<Account> accounts=new ArrayList<Account>();

Account account=new Account ();

account.setTotal(6.0);

accountreposity.save(account);  //accountreposity是我们定义的存储接口

accounts.add(account);

Person  person =new Person();

person.setAccounts(accounts);

personreposity.save(person); //personreposity是我们定义的存储接口


这样就成功的建立了DBref的关联储备插入。

在数据库中看到的 是类似这样的结构 那就引用成功了




使用

使用的时候

直接 List<Account> accounts=person.getAccounts();

就能取到了,非常方便。



0 0