准备:springboot 项目, mongodb,navicat工具
项目映入jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
1.mongodb集合和java对象映射
import lombok.Data;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
/**
* @description:
* @Author : lockie
* @Date : 2021/10/27
*/
@Data
@Document(collection = "user_document_test")
public class UserDocument extends BaseDocument{
private String id;
private String userName;
private Integer age;
@Indexed
private Integer status;
@Field("address")
private String address;
private Integer sex;
private String phone;
private String email;
private Integer pageNum = 1;
private Integer pageSize = 10;
}
@Id
主键,不可重复,自带索引,可以在定义的列名上标注,需要自己生成并维护不重复的约束。如果自己不设置@Id主键,mongo会自动生成一个唯一主键,并且插入时效率远高于自己设置主键。原因可参考上一篇mongo和mysql的性能对比。
在实际业务中不建议自己设置主键,应交给mongo自己生成,自己可以设置一个业务id,如int型字段,用自己设置的业务id来维护相关联的表。我这里设置了id字段,但是我并没有使用,还是用的mongodb生成的id,对应字段是_id
@Document
标注在实体类上,类似于hibernate的entity注解,标明由mongo来维护该表。注意:这里有个容易犯错的地方 @Document里面集合单词是 collection 而不是 collation
@Indexed
声明该字段需要加索引,加索引后以该字段为条件检索将大大提高速度。
唯一索引的话是@Indexed(unique = true)。
也可以对数组进行索引,如果被索引的列是数组时,MongoDB会索引这个数组中的每一个元素。
也可以对整个Document进行索引,排序是预定义的按插入BSON数据的先后升序排列。
也可以对关联的对象的字段进行索引,譬如User对关联的address.city进行索引。(注解怎么写还不清楚,待查)@Field
代表一个字段,可以不加,不加的话默认以参数名为列名。
import cn.hutool.core.date.DateUtil;
import lombok.Data;
import java.util.Date;
@Data
public class BaseDocument {
/**
* 创建人
*/
private String createBy;
/**
* 创建时间
*/
private String createTime;
/**
* 更新人
*/
private String updatedBy;
/**
* 更新时间
*/
private String updatedTime;
public void insertParam(String userName) {
String formatDateTime = DateUtil.formatDateTime(new Date());
this.setCreateBy(userName);
this.setCreateTime(formatDateTime);
this.setUpdatedBy(userName);
this.setUpdatedTime(formatDateTime);
}
public void updateParam(String userName) {
this.setUpdatedBy(userName);
this.setUpdatedTime(DateUtil.formatDateTime(new Date()));
}
}
2.创建service
import com.purcotton.notice.document.UserDocument;
import com.purcotton.obj.response.PageResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
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;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @description:
* @Author : lockie
* @Date : 2021/10/27
*/
@Slf4j
@Service
public class UserDocumentServiceImpl {
@Autowired
MongoTemplate mongoTemplate;
public static final String KEY = "user_document_test";
/**
* 增加
* @param userDocument
* @return
*/
public UserDocument addUser(UserDocument userDocument) {
userDocument.insertParam("admin");
UserDocument d = mongoTemplate.save(userDocument, KEY);
return d;
}
/**
* 分页查询
* @param userDocument
* @return
*/
public PageResponse<UserDocument> findUserPage(UserDocument userDocument) {
Query query = conditionQuery(userDocument);
long count = mongoTemplate.count(query, KEY);
query.limit(userDocument.getPageSize());
query.skip((long) (userDocument.getPageNum() - 1) * userDocument.getPageSize());
List<UserDocument> list = mongoTemplate.find(query, UserDocument.class, KEY);
PageImpl<UserDocument> page = new PageImpl<>(list, PageRequest.of(userDocument.getPageNum() - 1, userDocument.getPageSize()), count);
PageResponse<UserDocument> data = new PageResponse<>();
data.setPageNum(Long.parseLong(userDocument.getPageNum() + 1 + ""));
data.setPageSize(Long.parseLong(userDocument.getPageSize() + ""));
data.setList(page.toList());
data.setTotal(count);
return data;
}
/**
* 根据ID查询
* @param id
* @return
*/
public UserDocument findById(String id) {
UserDocument one = mongoTemplate.findById(id, UserDocument.class, KEY);
return one;
}
/**
* 查询所有的
* @return
*/
public List<UserDocument> findAll() {
return mongoTemplate.findAll(UserDocument.class, KEY);
}
/**
* 拼接查询条件
* @param userDocument
* @return
*/
private Query conditionQuery(UserDocument userDocument) {
Criteria c = new Criteria();
if (StringUtils.isNotEmpty(userDocument.getUserName())) {
// 模糊查询
c.and("userName").regex(".*" + userDocument.getUserName() + ".*");
}
if (userDocument.getStatus() != null) {
c.and("status").is(userDocument.getStatus());
}
if (userDocument.getAge() != null) {
// 大于等于小于等于查询
c.and("age").lte(userDocument.getAge()).gte(userDocument.getAge());
}
if (StringUtils.isNotEmpty(userDocument.getAddress())) {
c.and("address").regex("*." + userDocument.getAddress() + ".*");
}
if (StringUtils.isNotEmpty(userDocument.getPhone())) {
c.and("phone").is(userDocument.getPhone());
}
if (StringUtils.isNotEmpty(userDocument.getCreateTime())) {
c.and("createTime").gte(userDocument.getCreateTime());
}
Query query = new Query(c);
return query;
}
/**
* 根据条件查询
* @param userDocument
* @return
*/
public List<UserDocument> findByCondition(UserDocument userDocument) {
Query query = conditionQuery(userDocument);
List<UserDocument> list = mongoTemplate.find(query, UserDocument.class, KEY);
return list;
}
/**
* 根据ID更新
* @param userDocument
* @return
*/
public UserDocument update(UserDocument userDocument) {
if (StringUtils.isEmpty(userDocument.getId())) {
return null;
}
Query query = new Query(Criteria.where("_id").is(userDocument.getId()));
Update update = new Update();
update.set("userName",userDocument.getUserName());
update.set("age",userDocument.getAge());
update.set("status",userDocument.getStatus());
update.set("address",userDocument.getAddress());
update.set("sex",userDocument.getSex());
update.set("phone",userDocument.getPhone());
update.set("email",userDocument.getEmail());
userDocument.updateParam("admin");
mongoTemplate.updateFirst(query, update, KEY);
return findById(userDocument.getId());
}
/**
* 根据ID删除集合数据
* @param id
*/
public void deleteById(String id) {
Query query = new Query(Criteria.where("_id").is(id));
mongoTemplate.remove(query, KEY);
}
}
3.创建controller调用
import com.purcotton.notice.document.UserDocument;
import com.purcotton.notice.service.impl.UserDocumentServiceImpl;
import com.purcotton.obj.response.PageResponse;
import com.purcotton.obj.response.ResponseData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* @description:
* @Author : lockie
* @Date : 2021/10/27
*/
@Slf4j
@RestController
@RequestMapping("/user/document")
public class UserDocumentController {
@Autowired
UserDocumentServiceImpl userDocumentService;
/**
* 新增集合数据
* @param userDocument
* @return
*/
@PostMapping("/add")
public ResponseData<?> addUser(@RequestBody UserDocument userDocument) {
UserDocument u = userDocumentService.addUser(userDocument);
return ResponseData.success();
}
/**
* 分页查询集合数据
* @param userDocument
* @return
*/
@PostMapping("/getPage")
public ResponseData<PageResponse<UserDocument>> getPage(@RequestBody UserDocument userDocument) {
PageResponse<UserDocument> userPage = userDocumentService.findUserPage(userDocument);
return ResponseData.success(userPage);
}
/**
* 根据ID查询集合数据
* @param id
* @return
*/
@GetMapping("/findById")
public ResponseData<UserDocument> findById(String id) {
UserDocument user = userDocumentService.findById(id);
return ResponseData.success(user);
}
/**
* 查询所有的集合数据
* @return
*/
@GetMapping("/findAll")
public ResponseData<List<UserDocument>> findAll() {
List<UserDocument> all = userDocumentService.findAll();
return ResponseData.success(all);
}
/**
* 根据条件查询集合数据
* @param userDocument
* @return
*/
@PostMapping("/findByCondition")
public ResponseData<List<UserDocument>> findByCondition(@RequestBody UserDocument userDocument) {
List<UserDocument> list = userDocumentService.findByCondition(userDocument);
return ResponseData.success(list);
}
/**
* 更新集合数据
* @param userDocument
* @return
*/
@PostMapping("/update")
public ResponseData<UserDocument> update(@RequestBody UserDocument userDocument) {
return ResponseData.success(userDocumentService.update(userDocument));
}
/**
* 根据ID删除集合数据
* @param id
* @return
*/
@GetMapping("/deleteById")
public ResponseData deleteById(String id) {
userDocumentService.deleteById(id);
return ResponseData.success();
}
}