您的位置:首页 > 数据库 > Mongodb

Spring中Mongodb的java实体类映射

2017-02-16 14:19 387 查看


Spring中Mongodb的java实体类映射

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类

@Document(collection="person")
@CompoundIndexes({
@CompoundIndex(name = "age_idx", def = "{'lastName': 1, 'age': -1}", unique=true)
})
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;
}

@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类

1     @Document
2     public class Account {
3
4       @Id
5       private ObjectId id;
6       private Float total;
7
8     }


 
单列索引:@Indexed
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}") 
}) 
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: