依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
springboot 参数配置配置 (可以集群)
data:
mongodb:
uri: mongodb://172.0.0.1:27017, 172.0.0.1:27017, 172.0.0.1:27017
database: authTest
工具类
package cn.dabby.dsmp.utils;
import cn.dabby.common.ImgEnum;
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.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
@Component
public class MongoDBUitl {
//这个注入的是springbootjar包封装的工具类
@Autowired
private MongoTemplate mongoTemplate;
/**
* 描述:新增
* @author
* @created 2018/9/1 20:17
* @param imgEnum
* @return ResultObject
*/
public int insert(ImgEnum imgEnum) {
this.mongoTemplate.insert(imgEnum);
return HttpServletResponse.SC_OK;
}
/**
* 描述:删除
* @author
* @created 2018/9/1 20:17
* @param key
* @return ResultObject
*/
public int delete(String key) {
Query query = Query.query(Criteria.where("key").is(key));
this.mongoTemplate.remove(query, ImgEnum.class);
return HttpServletResponse.SC_OK;
}
/**
* 描述:修改
* @author
* @created 2018/9/1 20:17
* @param imgEnum
* @return ResultObject
*/
public int update(ImgEnum imgEnum) {
Query query = Query.query(Criteria.where("key").is(imgEnum.getKey()));
Update update = new Update();
update.set("baes64Img", imgEnum.getBaes64Img());
this.mongoTemplate.updateFirst(query, update, ImgEnum.class);
return HttpServletResponse.SC_OK;
}
/**
* 描述:查询
* @author
* @created 2018/9/1 20:17
* @param
* @return ResultObject
*/
public List<ImgEnum> query(String key) {
Query query = Query.query(Criteria.where("key").is(key));
List<ImgEnum> imgEnums = this.mongoTemplate.find(query, ImgEnum.class);
return imgEnums;
}
}
实体类
package cn.dabby.common;
import org.springframework.data.mongodb.core.mapping.Document;
/**
* @ClassName:ImgEnum
* @Description:
* @Author chenzhicai
* @Date:Created in 17:19 2019/2/25
* @Version:
*/
@Document(collection="user") //这个userMongodb的表明,若没有回自动新建
public class ImgEnum {
private String key;
private String baes64Img;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getBaes64Img() {
return baes64Img;
}
public void setBaes64Img(String baes64Img) {
this.baes64Img = baes64Img;
}
@Override
public String toString() {
return "ImgEnum{" +
"key='" + key + '\'' +
", baes64Img='" + baes64Img + '\'' +
'}';
}
}
test:
key=System.currentTimeMillis()+(int)(1+Math.random()*10)+"";
ImgEnum imgEnum=new ImgEnum();
imgEnum.setKey(key);
imgEnum.setBaes64Img(base64);
int count=mongoDBUitl.insert(imgEnum);