0
点赞
收藏
分享

微信扫一扫

Spring Data MongoDB--注解

yongxinz 2022-03-23 阅读 73


简介

        本文介绍spring-data-mongodb的注解的用法。

spring-data注解

@Id

简介

将相应字段设置为主键。 

  • 主键,不可重复,自带索引
  • 如果自己不设置@Id主键,mongo会自动生成一个唯一主键,并且插入时效率远高于自己设置主键。
  • 如果自己设置@Id主键,并标注在自定义的列名上,需要自己生成并维护不重复的约束。

示例

class Person {
@Id
Long id;

// ...
}

@Transient

简介

表示该属性不会被存到数据库(ORM框架将忽略该属性)。

示例

class Person {
@Transient
int age;
}

spring-data-mongodb注解

@Document

简介

标注在实体类上,把ava类声明为mongodb的文档,可以通过collection参数指定这个类对应的文档。

  • 如果没有设置 collection 值,则对应mongo中和 Java 类名相同的 collection
  • 如果设置了 collection 值,则对应mongo中对应的 collection

示例

// 该 bean 对应 mongo 中的 user collection
@Document
public class User{
}
// 该 bean 对应 mongo 中的 system_user collection
@Document(collection="system_user")
public class User{
}

@Indexed

简介

  • 索引,加索引后以该字段为条件检索将大大提高速度。
  • 对数组进行索引,MongoDB会索引这个数组中的每一个元素。
  • 对整个Document进行索引,排序是预定义的按插入BSON数据的先后升序排列。
  • 对关联的对象的字段进行索引,譬如User对关联的address.city进行索引。

示例

@Document(collection="system_user") 
public class User{
@Id
private String id;
//@Indexed(unique = true),唯一索引
@Indexed
private String userName;

}

@CompoundIndex

简介

  • 复合索引,加复合索引后通过复合索引字段查询将大大提高速度。

示例

@Document(collection="system_user") 
// userName和age将作为复合索引
// 数字参数指定索引的方向,1为正序,-1为倒序
@CompoundIndexes({
@CompoundIndex(name = "userName_age_idx", def = "{'userName': 1, 'age': -1}")
})
public class User{
@Id
private String id;
private String userName;
private String age;

}

@Field

简介

  • 配置MongoDB持久化保存文档时要使用的字段的名称

示例

@Document
class User {
@Field("email")
String emailAddress;
}

@Query

简介

在MongoDB存储库方法上提供查询

示例

@Query("{ 'name' : ?0 }")
List<User> findUsersByName(String name);

@DBRef

简介

  • 关联另一个document对象

示例

public class User{
@DBRef
private List<Role> roles;
}

@EnableMongoRepositories

简介

开启MongoDB存储库



举报

相关推荐

0 条评论