MongoDB——》SpringBoot中MongoDB注解概念及使用

版权声明:本文为博主原创文章,无需授权即可转载,甚至无需保留以上版权声明,转载时请务必注明作者。
https://blog.csdn.net/weixin_43453386/article/details/86007121

一、@Document : 文档

1、概念

  • 标注在实体类上,把ava类声明为mongodb的文档,可以通过collection参数指定这个类对应的文档
  • 类似于hibernate的entity注解,标明由mongo来维护该表

2、用法

@Document(collection="mongodb 对应 collection 名")

  • 如果没有设置 collection 值,则对应mongo中和 Java 类名相同的 collection
// 该 bean 对应 mongo 中的 user collection
@Document
public class User{
}
  • 如果设置了 collection 值,则对应mongo中对应的 collection
// 该 bean 对应 mongo 中的 system_user collection
@Document(collection="system_user") 
public class User{
}

二、@Id : 主键

1、概念

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

2、用法

// 该 bean 对应 mongo 中的 system_user collection
@Document(collection="system_user") 
public class User{
    @Id
    private String id;
}

三、@Indexed : 索引

1、概念

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

2、用法

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

四、@CompoundIndex : 联合索引

1、概念

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

2、用法

@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 : 属性

1、概念

  • 代表一个字段
  • 加这个注解,就是以注解的值对应mongo的key
  • 不加这个注解,默认以参数对应mongo的key

2、用法

@Document(collection="system_user") 
@CompoundIndexes({
    @CompoundIndex(name = "userName_age_idx", def = "{'userName': 1, 'age': -1}")
})
public class User{
    @Id
    private String id;
    //在 java bean 中字段名为 userName,存储到 mongo 中 key 为 user_name
    @Field("user_name")
    private String userName;
    //在 java bean 中字段名为 age,存储到 mongo 中 key 为 age
    private String age;
}

六、@Transient: 属性

1、概念

  • 不会被录入到数据库中,只作为普通的javaBean属性。

2、用法

@Document(collection="system_user") 
@CompoundIndexes({
    @CompoundIndex(name = "userName_age_idx", def = "{'userName': 1, 'age': -1}")
})
public class User{
    @Id
    private String id;
    @Field("user_name")
    private String userName;
    private String age;
    //@Transient
    private String local;
}

七、@DBRef: 关联实体

1、概念

  • 关联另一个document对象

2、用法

@Document(collection="system_user") 
@CompoundIndexes({
    @CompoundIndex(name = "userName_age_idx", def = "{'userName': 1, 'age': -1}")
})
public class User{
    @Id
    private String id;
    @Field("user_name")
    private String userName;
    private String age;
    //@Transient
    private String local;
    @DBRef
    private List<Role> roles;
}

猜你喜欢

转载自blog.csdn.net/weixin_43453386/article/details/86007121