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中取出的数据。

@Field("stock_name") - 映射数据里面的字段,否则存放到数据库里面的字段名字跟实体类变量名一样
 private String stockName = “”;

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

 

Person类

@Document(collection="person")
@CompoundIndexes({
@CompoundIndex(name="age_idx",def="{'lastName':1,'age':-1}")
})
publicclassPerson<TextendsAddress>{

@Id
privateStringid;
@Indexed(unique=true)
privateIntegerssn;
privateStringfirstName;
@Indexed
privateStringlastName;
privateIntegerage;
@Transient
privateIntegeraccountTotal;
@DBRef
privateList<Account>accounts;
privateTaddress;


publicPerson(Integerssn){
this.ssn=ssn;
}

@PersistenceConstructor
publicPerson(Integerssn,StringfirstName,StringlastName,Integerage,Taddress){
this.ssn=ssn;
this.firstName=firstName;
this.lastName=lastName;
this.age=age;
this.address=address;
}

Account类

@Document
publicclassAccount{

@Id
privateObjectIdid;
privateFloattotal;

}

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}") }) 

 

转载于:https://my.oschina.net/hfq/blog/1816508

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值