3.spring项目中mongodb相关注解说明

import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;

import java.io.Serializable;
import java.util.Date;

@Data
@Document(collection = "Student")
public class Student implements Serializable {
    @Id// 必须指定id列
    private String studentId;

    @Field("studentName") //映射文档表中的某个不同命名字段
    private String studentName;

    private Integer studentAge;
    @Indexed //该字段需要加索引
    private Double studentScore;

    private Date studentBirthday;
}

1.@Id
主键,不可重复,自带索引

2.@Document
标注在实体类上,类似于hibernate的entity注解,标明由mongo来维护该表
org.springframework.data.mongodb.core.mapping.Document.class
把一个java类声明为mongodb的文档,可以通过collection参数指定这个类对应的文档。
@Document(collection=“mongodb 对应 collection 名”)

// 若未加 @Document ,该 bean save 到 mongo 的 user collection
// 若添加 @Document ,则 save 到 reUser collection
@Document(collection=“reUser”)
public class User{
}

3.@Indexed
声明该字段需要加索引,加索引后以该字段为条件检索将大大提高速度。
唯一索引的话是@Indexed(unique = true)。
也可以对数组进行索引,如果被索引的列是数组时,MongoDB会索引这个数组中的每一个元素。
也可以对整个Document进行索引,排序是预定义的按插入BSON数据的先后升序排列。

4.@CompoundIndex
复合索引,加复合索引后通过复合索引字段查询将大大提高速度。
@Document
@CompoundIndexes({
@CompoundIndex(name = “age_idx”, def = “{‘lastName’: 1, ‘age’: -1}”)
})
public class Person {
}

写法如上,lastName和age将作为复合索引,数字参数指定索引的方向,1为正序,-1为倒序。方向对单键索引和随机存不要紧,
但如果你要执行分组和排序操作的时候,它就非常重要了。

5.@Field
代表一个字段,可以不加,不加的话默认以参数名为列名。
给映射存储到 mongodb 的字段取别名
在 java bean 中字段名为 firstName,存储到 mongo 中 key 为 fName
@Field(“fName”)
private String firstName;

6.@Transient
被该注解标注的,将不会被录入到数据库中。只作为普通的javaBean属性。

7.@DBRef
关联另一个document对象。类似于mysql的表关联,但并不一样,mongo不会做级联的操作。

8.注解@JsonFormat:后端格式化日期后返回给前端
@JsonFormat(pattern = “yyyy-MM-dd”, timezone = “GMT+8”)
private Date birthday;//生日

@JsonFormat(pattern = “yyyy-MM-dd HH:mm:ss”, timezone = “GMT+8”)
private Date createTime;//创建时间

@JsonFormat(pattern = DateUtils.LONG_TIME_FORMAT, timezone = “GMT+8”)
private Date modifyTime;//修改时间


版权声明:本文为huangchong0107原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。