首先要有一个springboot的项目
第一步,pom.xml导包
org.springframework.boot
spring-boot-starter-data-mongodb
import org.springframework.data.mongodb.core.query.Update;
public class UpdateQuery {
private Update update = new Update();
public Update getUpdate() {
return update;
}
public void setUpdate(Update update) {
this.update = update;
}
public UpdateQuery setQuery(String property, Object value) {
update.set(property, value);
return (UpdateQuery) this;
}
}
import java.util.List;
import org.ewhl.common.pojo.UpdateQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
/**
*
* @ClassName BaseMongoService
* @Description
* @author ZhangPneg
* @Date 2019-03-29 16:17:29
* @version 1.0.0
* @param
*/
public class BaseMongoService {
@Autowired
private MongoTemplate mongoTemplate;
/**
*
* @Description 插入对象
* @param mongo mongo对象
* @return
* Create at: 2019-03-29 16:10:55
* @author: ZhangPneg
* Revision:
* 2019-03-29 16:10:55 - first revision by ZhangPneg
*
*/
public String insert(T mongo) {
try {
mongoTemplate.save(mongo);
return "success";
} catch (Exception e) {
e.printStackTrace();
return "error";
}
}
/**
*
* @Description 设置id
* @param id
* @return
* Create at: 2019-03-29 16:12:02
* @author: ZhangPneg
* Revision:
* 2019-03-29 16:12:02 - first revision by ZhangPneg
*
*/
public Query setId(String id) {
Query query = new Query(Criteria.where("_id").is(id));
return query;
}
/**
*
* @Description 获取UpdateQuery
* @return
* Create at: 2019-03-29 16:12:33
* @author: ZhangPneg
* Revision:
* 2019-03-29 16:12:33 - first revision by ZhangPneg
*
*/
public UpdateQuery getUpdateQuery() {
return new UpdateQuery();
}
/**
*
* @Description 根据id更新
* @param query setId的query
* @param up update对象
* @param entityClass 对象class
* @return
* Create at: 2019-03-29 16:13:09
* @author: ZhangPneg
* Revision:
* 2019-03-29 16:13:09 - first revision by ZhangPneg
*
*/
public String updateById(Query query,UpdateQuery up,Class entityClass) {
try {
mongoTemplate.updateFirst(query, up.getUpdate(), entityClass);
return "success";
} catch (Exception e) {
e.printStackTrace();
return "error";
}
}
/**
*
* @Description 查询全部
* @param entityClass 对象class
* @return
* Create at: 2019-03-29 16:14:57
* @author: ZhangPneg
* Revision:
* 2019-03-29 16:14:57 - first revision by ZhangPneg
*
*/
public List findAll(Class entityClass) {
return mongoTemplate.findAll(entityClass);
}
/**
*
* @Description 根据id查询
* @param id
* @param entityClass 对象class
* @return
* Create at: 2019-03-29 16:16:20
* @author: ZhangPneg
* Revision:
* 2019-03-29 16:16:20 - first revision by ZhangPneg
*
*/
public T selectById(String id,Class entityClass) {
Query query = new Query(Criteria.where("_id").is(id));
return mongoTemplate.findOne(query, entityClass);
}
/**
*
* @Description 根据Criteria查询
* @param criteria
* @param entityClass 对象class
* @return
* Create at: 2019-03-29 16:17:57
* @author: ZhangPneg
* Revision:
* 2019-03-29 16:17:57 - first revision by ZhangPneg
*
*/
public List select(Criteria criteria,Class entityClass) {
Query query = new Query();
query.addCriteria(criteria);
return mongoTemplate.find(query, entityClass);
}
/**
*
* @Description 删除对象
* @param mongo mongo对象
* @return
* Create at: 2019-03-29 16:18:45
* @author: ZhangPneg
* Revision:
* 2019-03-29 16:18:45 - first revision by ZhangPneg
*
*/
public String delete(T mongo) {
try {
mongoTemplate.remove(mongo);
return "success";
} catch (Exception e) {
e.printStackTrace();
return "error";
}
}
/**
*
* @Description 根据id删除
* @param id
* @param entityClass 对象class
* @return
* Create at: 2019-03-29 16:20:10
* @author: ZhangPneg
* Revision:
* 2019-03-29 16:20:10 - first revision by ZhangPneg
*
*/
public String deleteById(String id,Class entityClass) {
try {
T mongo = selectById(id,entityClass);
delete(mongo);
return "success";
} catch (Exception e) {
e.printStackTrace();
return "error";
}
}
}
第四步创建要存入mongodb的实体类(以DataEntry为例)
/*
import java.io.Serializable;
import java.math.BigDecimal;
import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper=false)
@Table(name=“data_entry”)
public class DataEntry implements Serializable {
private static final long serialVersionUID = 1L;
/**
*
*/
@Id
@Column(name = "id")
private Integer id;
/**
* 分类Id
*/
@Column(name = "data_class_id")
private Integer dataClassId;
/**
* 分类名称
*/
@Column(name = "data_class_name")
private String dataClassName;
/**
* 标题
*/
@Column(name = "data_title")
private String dataTitle;
/**
* 添加时间
*/
@Column(name = "create_time")
private Timestamp createTime;
/**
* 内容
*/
@Column(name = "content")
private String content;
/**
* 上传人id
*/
@Column(name = "userId")
private Long userId;
/**
* 上传人登录名
*/
@Column(name = "userLoginName")
private String userLoginName;
@Transient
private Timestamp startTime;
@Transient
private Timestamp endTime;
public DataEntry(){
}
public DataEntry(
Integer id
){
this.id = id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return this.id;
}
public void setDataClassId(Integer dataClassId) {
this.dataClassId = dataClassId;
}
public Integer getDataClassId() {
return this.dataClassId;
}
public void setDataClassName(String dataClassName) {
this.dataClassName = dataClassName;
}
public String getDataClassName() {
return this.dataClassName;
}
public void setDataTitle(String dataTitle) {
this.dataTitle = dataTitle;
}
public String getDataTitle() {
return this.dataTitle;
}
public void setCreateTime(Timestamp createTime) {
this.createTime = createTime;
}
public Timestamp getCreateTime() {
return this.createTime;
}
public void setContent(String content) {
this.content = content;
}
public String getContent() {
return this.content;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getUserLoginName() {
return userLoginName;
}
public void setUserLoginName(String userLoginName) {
this.userLoginName = userLoginName;
}
public Timestamp getStartTime() {
return startTime;
}
public void setStartTime(Timestamp startTime) {
this.startTime = startTime;
}
public Timestamp getEndTime() {
return endTime;
}
public void setEndTime(Timestamp endTime) {
this.endTime = endTime;
}
}
这个实体类就是对应的mongodb中的表,一个实体类一个表,实体类的的属性就是表中的字段,当插入一个此类型的值时就是在对应的表中插入一条数据
第五步创建DataEntryService extends BaseMongoService,在这里要注意一定要继承BaseMongoService类,因为我们要调用的都是BaseMongoService的方法,以实现代码的复用,在项目中所有要存入mongodb的都可以通过继承BaseMongoService类实现
import org.springframework.beans.factory.annotation.Autowired;
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.stereotype.Service;
import java.util.List;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
@Service
public class DataEntryService extends BaseMongoService {
@Autowired
private MongoTemplate mongoTemplate;
public class ArticleService extends BaseMongoService {
@Autowired
private MongoTemplate mongoTemplate;
public PagerUtil getPage(Article article, Integer currentPage, Integer pageSize){
// 创建查询对象
Query query = new Query();
// 设置起始数
query.skip((currentPage - 1) * pageSize);
// 设置查询条数
query.limit(pageSize);
// 创建条件对象
Criteria criteria = new Criteria();
if (StringUtils.isNotBlank(article.getArticleTitle())) {
// 文章名的正则
Pattern pattern = Pattern.compile("^.*" + article.getArticleTitle() + ".*$", Pattern.CASE_INSENSITIVE);
// 添加文章名模糊查询条件
criteria.and("articleTitle").regex(pattern);
}
query.addCriteria(criteria);
// 查询当前页数据集合
List list = mongoTemplate.find(query, Article.class);
// 查询总记录数
long count = mongoTemplate.count(query, Article.class);
// 创建分页实体对象
return new PagerUtil(list, count);
}
}
因为牵扯到分页查询,所以在这里重写了分页
mongodb中所有的存、取动作都是通过MongoTemplate来实现
第六步,配置mongodb的连接,因为这个项目使用的是分布式,所以在用的时候只在所需调用的工程上配置mongodb的连接,
data:
mongodb:
host: XX.98.53.XX
port: 27017
database: huayu #指定操作的数据库
(也就是所要连接的数据库名称,前提是要提前在mongodb中创建此名称数据库,创建方法…往后看)
但是此处有个坑,就是可能是因为我把mongodb的包导在了公共工程中,所以导致只要调用此公共工程的服务如果不配置mongodb的连接都会导致报错
com.mongodb.MongoSocketOpenException: Exception opening socket
at com.mongodb.connection.SocketStream.open(SocketStream.java:62) ~[mongodb-driver-core-3.6.4.jar:na]
at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:126) ~[mongodb-driver-core-3.6.4.jar:na]
at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:114) ~[mongodb-driver-core-3.6.4.jar:na]
at java.lang.Thread.run(Unknown Source) [na:1.8.0_191]
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method) ~[na:1.8.0_191]
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source) ~[na:1.8.0_191]
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source) ~[na:1.8.0_191]
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source) ~[na:1.8.0_191]
at java.net.AbstractPlainSocketImpl.connect(Unknown Source) ~[na:1.8.0_191]
at java.net.PlainSocketImpl.connect(Unknown Source) ~[na:1.8.0_191]
at java.net.SocksSocketImpl.connect(Unknown Source) ~[na:1.8.0_191]
at java.net.Socket.connect(Unknown Source) ~[na:1.8.0_191]
at com.mongodb.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:59) ~[mongodb-driver-core-3.6.4.jar:na]
at com.mongodb.connection.SocketStream.open(SocketStream.java:57) ~[mongodb-driver-core-3.6.4.jar:na]
... 3 common frames omitted
测试TestController
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(“home”)
public class TestController {
@Autowired
private CaseReportService caseReportService;
@Autowired
private DataEntryService dataEntryService;
@PostMapping("findAll")
public List findAll(){
return caseReportService.findAll(CaseReport.class);
}
@PostMapping("insert")
public String insert() {
CaseReport caseReport = new CaseReport();
caseReport.setTreatmentRecord("吃的太多");
return caseReportService.insert(caseReport);
}
@PostMapping("insertDataEntryService")
public String insertDataEntryService() {
DataEntry dataEntry = new DataEntry();
dataEntry.setId(85);
return dataEntryService.insert(dataEntry);
}
@PostMapping("findAllDataEntry")
public List findAllDataEntry(){
return dataEntryService.findAll(DataEntry.class);
}
}
附,其他类测试方法
package org.ewhl.web;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("home")
public class TestController {
@Autowired
CmsService cmsService;
@PostMapping("insert")
public String insert() {
Cms cms = new Cms();
cms.setImg("http://www.baidu.com");
cms.setCreateTime(new Date());
return cmsService.insert(cms);
}
@PostMapping("findAll")
public List findAll() {
return cmsService.findAll(Cms.class);
}
@PostMapping("testPage")
public PagerUtil findPage(String pageNumber,String pageSize,String start,String end,String title){
Cms cms = new Cms();
cms.setTitle(title);
return cmsService.getPage(cms, Integer.parseInt(pageNumber), Integer.parseInt(pageSize), start, end);
}
@PostMapping("update")
public String update() {
UpdateQuery update = cmsService.getUpdateQuery();
Query query = cmsService.setId("5c9db407e0d3185c56cd09ba");
update.setQuery("img", "www.dubai.com.cn").setQuery("createTime", new Date());
return cmsService.updateById(query, update, Cms.class);
}
@PostMapping("select")
public List select(Cms cms) {
Criteria criteria = new Criteria();
// 设备名的正则
Pattern pattern = Pattern.compile("^.*" + cms.getImg() + ".*$", Pattern.CASE_INSENSITIVE);
// 添加设备名模糊查询条件
criteria.and("img").regex(pattern);
return cmsService.select(criteria, Cms.class);
}
@PostMapping("selectById")
public Cms selectById(String id) {
return cmsService.selectById(id, Cms.class);
}
@PostMapping("deleteById")
public String deleteById(String id) {
return cmsService.deleteById(id, Cms.class);
}
}
第一次接触mongodb,着急只是学会了怎么使用,具体的理解还不太清楚,后期补上