第一步:【pom.xml】
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
第二步:【application.properties】
spring.data.mongodb.uri=mongodb://127.0.0.1:27017/demo
第三步:【实体类】
package com.isci.po;
import org.springframework.data.mongodb.core.mapping.Document;
/**
* @author saiwaiwunong
* @desc
* @date 2018/11/17 15:04
*/
@Document(collection = "user")
public class User {
private String id;
private String userName;
private String password;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
@Id - 文档的唯一标识,在mongodb中为ObjectId,它是唯一的,通过时间戳+机器标识+进程ID+自增计数器(确保同一秒内产生的Id不会冲突)构成
@Document - 把一个java类声明为mongodb的文档,可以通过collection参数指定这个类对应的文档
@DBRef - 声明类似于关系数据库的关联关系。ps:暂不支持级联的保存功能,当你在本实例中修改了DERef对象里面的值时,单独保存本实例并不能保存DERef引用的对象,它要另外保存,如下面例子的Person和Account
@Indexed - 声明该字段需要索引,建索引可以大大的提高查询效率
@CompoundIndex - 复合索引的声明,建复合索引可以有效地提高多字段的查询效率
@GeoSpatialIndexed - 声明该字段为地理信息的索引
@Transient - 映射忽略的字段,该字段不会保存到mongodb
@PersistenceConstructor - 声明构造函数,作用是把从数据库取出的数据实例化为对象。该构造函数传入的值为从DBObject中取出的数据
【基本操作】
#code ...
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
#code ...
@Autowired
MongoTemplate mongoTemplate
#code ...
private void insert() throws Exception {
User user = new User();
user.setPassword("4");
user.setUserName("4");
mongoTemplate.insert(user);
}
private void delete1() throws Exception {
Query query = Query.query(Criteria.where("id").is("3"));
mongoTemplate.remove(query, User.class);
}
private void delete2() throws Exception {
User user = mongoTemplate.findById("3", User.class);
mongoTemplate.remove(user);
}
private void updateFirst() throws Exception {
Query query = Query.query(Criteria.where("id").is("3"));
Update param = new Update();
param.set("userName", "xiaohong");
param.set("password", "111111");
mongoTemplate.updateFirst(query, param, User.class);
}
private void update() throws Exception{
User user = new User();
user.setId("2");
user.setUserName("dongdaye");
mongoTemplate.save(user);
}
private void find() throws Exception {
Query query = Query.query(Criteria.where("userName").is("xiaohong"));
List<User> user = mongoTemplate.find(query, User.class);
}
private void findAll() throws Exception {
List<User> user = mongoTemplate.findAll(User.class);
}
private void findById() throws Exception {
User user = mongoTemplate.findById("3", User.class);
}
网友评论