Spring中Mongodb的java实体类映射

来源:互联网 发布:浙江华为 知乎 编辑:程序博客网 时间:2024/05/19 13:26

spring-data-mongodb中的实体映射是通过MongoMappingConverter这个类实现的。它可以通过注释把java类转换为mongodb的文档。

它有以下几种注释:
@Id - 文档的唯一标识,在mongodb中为ObjectId,它是唯一的,通过时间戳+机器标识+进程ID+自增计数器(确保同一秒内产生的Id不会冲突)构成。

@Document - 把一个java类声明为mongodb的文档,可以通过collection参数指定这个类对应的文档。

@DBRef - 声明类似于关系数据库的关联关系。ps:暂不支持级联的保存功能,当你在本实例中修改了DERef对象里面的值时,单独保存本实例并不能保存DERef引用的对象,它要另外保存,如下面例子的Person和Account。

@Indexed - 声明该字段需要索引,建索引可以大大的提高查询效率。

@CompoundIndex - 复合索引的声明,建复合索引可以有效地提高多字段的查询效率。

@GeoSpatialIndexed - 声明该字段为地理信息的索引。

@Transient - 映射忽略的字段,该字段不会保存到mongodb。

@PersistenceConstructor - 声明构造函数,作用是把从数据库取出的数据实例化为对象。该构造函数传入的值为从DBObject中取出的数据。

以下引用一个官方文档的例子:


Person类

[java] view plain copy
  1. @Document(collection="person")    
  2. @CompoundIndexes({    
  3.     @CompoundIndex(name = "age_idx", def = "{'lastName': 1, 'age': -1}")    
  4. })    
  5. public class Person<T extends Address> {    
  6.     
  7.   @Id    
  8.   private String id;    
  9.   @Indexed(unique = true)    
  10.   private Integer ssn;    
  11.   private String firstName;    
  12.   @Indexed    
  13.   private String lastName;    
  14.   private Integer age;    
  15.   @Transient    
  16.   private Integer accountTotal;    
  17.   @DBRef    
  18.   private List<Account> accounts;    
  19.   private T address;    
  20.     
  21.       
  22.   public Person(Integer ssn) {    
  23.     this.ssn = ssn;    
  24.   }    
  1.  @PersistenceConstructor    
  2.   public Person(Integer ssn, String firstName, String lastName, Integer age, T address) {    
  3.     this.ssn = ssn;    
  4.     this.firstName = firstName;    
  5.     this.lastName = lastName;    
  6.     this.age = age;    
  7.     this.address = address;    
  8.   }    


Account类


[java] view plain copy
  1. @Document    
  2. public class Account {    
  3.     
  4.   @Id    
  5.   private ObjectId id;    
  6.   private Float total;    
  7.     
  8. }   

spring data 4 mongoDB自动创建复合索引
spring data 4 mongodb 在domain上添加annation,自动创建复合索引时需要使用CompoundIndexes。

例如:
 
@CompoundIndex(name = "shop_index", def = "{platform : 1, shopId : 1}") 
程序也不会有编译错误或者执行错误,但是spring data不会建立任何索引, 
下面这样写才会启动时自动建立复合索引。 
 
@CompoundIndexes({ 
     @CompoundIndex(name = "shop_index", def = "{platform : 1, shopId : 1}") 
}) 
 
原创粉丝点击