一.pom.xml
org.springframework.boot
spring-boot-starter-parent
1.5.10.RELEASE
…
org.springframework.data
spring-data-mongodb
org.springframework.boot
spring-boot-starter-data-mongodb
org.mongodb
mongo-java-driver
…
2.Mongo配置类
在config包中拷入配置文件夹mongodb
并在application-xxx.yml中配置:
spring:
data:
mongodb:
primary:
uri: mongodb://IP:PORT/DBNAME
authentication-database: false
三.使用
1.在使用的类中注入:
@Resource
private MongoTemplate mongoTemplate;
2.注意:mongo存储Decimal128,java运算用Decimal
@Autowired
private Decimal128ToBigDecimalConverter decimal128ToBigDecimalConverter;
例如:
Decimal a = decimal128ToBigDecimalConverter.convert((Decimal128)***)
3.Mongo的聚合查询:
Aggregation agg = Aggregation.newAggregation(
Aggregation.match(criteria),
Aggregation.group("ingredientName").sum("saleCupNum").as("saleNumber"),
Aggregation.project("ingredientName", "saleNumber").and("ingredientName").previousOperation(),
Aggregation.sort(Sort.Direction.DESC, "saleNumber")
);
AggregationResults outputType = mongoTemplate.aggregate(agg, "drink_day_statics_view", DataSalesStructureHistogramIngredientBo.class);
spring.data.mongodb.uri=mongodb://localhost:27017/ttt #连接地址 没密码
spring.data.mongodb.authentication-database=false #没密码的意思
package com.sdyy.springboot.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.convert.MongoConverter;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoClientURI;
import com.mongodb.ReadPreference;
import com.sdyy.common.mongodb.MongoTemplateHelper;
/**
* @author li
* @ClassName PrimaryMongoConfig
* @date: 2019年7月8日 下午12:55:33
*/
@Configuration
public class PrimaryMongoConfig {
@Autowired
private MappingMongoConverter customConverter;
@Primary
@Bean
@ConfigurationProperties(prefix = "spring.data.mongodb")
public MongoProperties primaryMongoProperties() {
return new MongoProperties();
}
@Bean(name = "mongoTemplate")
@Primary
public MongoTemplate primaryMongoTemplate() throws Exception {
return new MongoTemplate(primaryFactory(primaryMongoProperties()), (MongoConverter) customConverter);
}
@Bean
@Primary
public MongoDbFactory primaryFactory(MongoProperties mongoProperties) throws Exception {
System.out.println("uri:" + primaryMongoProperties().getUri());
MongoClientOptions.Builder options = new MongoClientOptions.Builder();
options.readPreference(ReadPreference.secondary());
options.connectionsPerHost(10);
return new SimpleMongoDbFactory(new MongoClientURI(primaryMongoProperties().getUri(), options));
}
}
package com.sdyy.springboot.config;
import java.util.ArrayList;
import java.util.List;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.convert.CustomConversions;
import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
import com.sdyy.common.mongodb.converter.BigDecimalToDecimal128Converter;
import com.sdyy.common.mongodb.converter.Decimal128ToBigDecimalConverter;
/**
* @author li
* @ClassName MongoCustomConverter
* @date: 2019年7月8日 下午12:55:23
*/
@Configuration
public class MongoCustomConverter {
@Bean(name = "customConverter")
public MappingMongoConverter customConversions(MongoDbFactory factory, MongoMappingContext context) {
DefaultDbRefResolver dbRefResolver = new DefaultDbRefResolver(factory);
MappingMongoConverter converter = new MappingMongoConverter(dbRefResolver, context);
List> converterList = new ArrayList<>();
converterList.add(new BigDecimalToDecimal128Converter());
converterList.add(new Decimal128ToBigDecimalConverter());
converter.setCustomConversions(new CustomConversions(converterList));
return converter;
}
}
package com.sdyy.common.mongodb.dao;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import javax.annotation.Resource;
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 com.sdyy.common.mongodb.page.Page;
public class MongoBaseDao {
private static final int DEFAULT_SKIP = 0;
private static final int DEFAULT_LIMIT = 200;
/**
* spring mongodb 集成操作类
*/
@Resource
protected MongoTemplate mongoTemplate;
protected String collection;
/**
* 通过条件查询实体(集合)
*
* @param query
*/
public List find(Query query) {
return mongoTemplate.find(query, this.getEntityClass());
}
public List find(Query query, String collectionName) {
return mongoTemplate.find(query, this.getEntityClass(), collectionName);
}
/* public List findtest(Query query, String collectionName) {
return mongoTemplate.find(query,OrdersBo.class,collectionName);
}
*/
/**
* 通过一定的条件查询一个实体
*
* @param query
* @return
*/
public T findOne(Query query) {
return mongoTemplate.findOne(query, this.getEntityClass());
}
public T findOne(Query query, String collectionName) {
return mongoTemplate.findOne(query, this.getEntityClass(), collectionName);
}
/**
* 通过条件查询更新数据
*
* @param query
* @param update
* @return
*/
public void update(Query query, Update update) {
mongoTemplate.findAndModify(query, update, this.getEntityClass());
}
public void update(Query query, Update update, String collectionName) {
mongoTemplate.findAndModify(query, update, this.getEntityClass(), collectionName);
}
public void removeById(String id, String collectionName){
Query query = new Query();
query.addCriteria(Criteria.where("_id").is(id));
mongoTemplate.remove(query, collectionName);
}
/**
* 保存一个对象到mongodb
*
* @param entity
* @return
*/
public T save(T entity) {
mongoTemplate.insert(entity);
return entity;
}
public T save(T entity, String collectionName) {
mongoTemplate.insert(entity, collectionName);
return entity;
}
/**
* 通过ID获取记录
*
* @param id
* @return
*/
public T findById(String id) {
return mongoTemplate.findById(id, this.getEntityClass());
}
/**
* 通过ID获取记录,并且指定了集合名(表的意思)
*
* @param id
* @param collectionName
* 集合名
* @return
*/
public T findById(String id, String collectionName) {
return mongoTemplate.findById(id, this.getEntityClass(), collectionName);
}
/**
* 分页查询
* @param page
* @param query
* @return
*/
public Page findPage(Page page, Query query){
long count = this.count(query);
page.setTotal(count);
int pageNumber = page.getPagenumber();
int pageSize = page.getPageSize();
query.skip((pageNumber - 1) * pageSize).limit(pageSize);
List rows = this.find(query);
page.setRows(rows);
return page;
}
public Page findPage(Page page, Query query, String collectionName){
long count = this.count(query, collectionName);
page.setTotal(count);
int pageNumber = page.getPagenumber();
int pageSize = page.getPageSize();
query.skip((pageNumber - 1) * pageSize).limit(pageSize);
List rows = this.find(query, collectionName);
page.setRows(rows);
return page;
}
/**
* 求数据总和
* @param query
* @return
*/
public long count(Query query){
return mongoTemplate.count(query, this.getEntityClass());
}
public long count(Query query, String collectionName){
return mongoTemplate.count(query, this.getEntityClass(), collectionName);
}
/**
* 获取需要操作的实体类class
*
* @return
*/
public Class getEntityClass(){
//Type superclass = this.getClass().getGenericSuperclass();
//Type[] actualTypeArguments = ((ParameterizedType)superclass).getActualTypeArguments();
// return (Class) actualTypeArguments[0];
Class tClass = (Class)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];
return tClass;
}
/** /**
* @description: 查询语句生成
* @param map 条件与排序 LiistMap key与value说明 精确匹配: WHERE_KEY:条件的列,WHERE_VALUE条件的值
模糊搜索 : VAGUE_SEARCH_KEY 条件的列,VAGUE_SEARCH_VALUE 条件的值
sort排序:SORT_KEY 排序的字段 SORT_VALUE ASC(1) OR DESC(-1)
in 查询 IN_SEARCH_KEY in 字段 IN_SEARCH_VALUE in的list值>
* @return ${return_type}
* @throws
* @author lizz
* @date 2019/7/9 18:57
*/
public Query createQuery(List
//模糊搜素
String vagueSearchKey=MapUtils.getStringFromMap(map.get(i),VAGUE_SEARCH_KEY);
String vagueSearchValue=MapUtils.getStringFromMap(map.get(i),VAGUE_SEARCH_VALUE);
if(!StringUtils.isEmpty(vagueSearchKey)&&!StringUtils.isEmpty(vagueSearchValue)){
Pattern pattern = Pattern.compile("^.*" + vagueSearchValue + ".*$");
query.addCriteria(Criteria.where(vagueSearchKey).regex(pattern));
}
//in查询
String inSearchKey=MapUtils.getStringFromMap(map.get(i),IN_SEARCH_KEY);
List inSearchValue=(List ) map.get(i).get(IN_SEARCH_VALUE);;
if(!StringUtils.isEmpty(inSearchKey)&&inSearchValue!=null){
query.addCriteria(Criteria.where(inSearchKey).in(inSearchValue));
}
//not in 查询
String notInSearchKey=MapUtils.getStringFromMap(map.get(i),NOT_IN_SEARCH_KEY);
List notInSearchValue=(List ) map.get(i).get(NOT_IN_SEARCH_VALUE);;
// String notInSearchValue=MapUtils.getStringFromMap(map.get(i),NOT_IN_SEARCH_VALUE);
if(!StringUtils.isEmpty(notInSearchKey)&&!StringUtils.isEmpty(notInSearchValue)){
criteria.and(notInSearchKey).nin(notInSearchValue);
query.addCriteria(criteria);
// query.addCriteria(Criteria.where(notInSearchKey).nin(notInSearchValue));
}
String sortKey=MapUtils.getStringFromMap(map.get(i),SORT_KEY);
String sortValue=MapUtils.getStringFromMap(map.get(i),SORT_VALUE);
// 排序
if (sortKey!=null&&sortValue!=null) {
Sort Sort= new Sort("");
query.with(Sort.and(new Sort(sortKey, sortValue)));
}
String startTime = MapUtils.getStringFromMap(map.get(i),START_TIME);
String endTime = MapUtils.getStringFromMap(map.get(i),END_TIME);
String Time = MapUtils.getStringFromMap(map.get(i),TIME);
if (startTime!=null&&endTime!=null&&Time!=null) {
query.addCriteria(Criteria.where(Time).gte(DateUtils.parseDate(DATE_FORMAT,startTime)).lte(DateUtils.parseDate(DATE_FORMAT,endTime)));
}
}
return query;
}
/** /**
* @description: 根据传入条件查询
* @param map 条件与排序
* @return ${return_type}
* @throws
* @author lizz
* @date 2019/7/9 20:48
*/
public List selectByCondition(List
package com.sdyy.biz.licence.maint.mappers;
import org.springframework.stereotype.Component;
import com.sdyy.biz.licence.maint.entity.TestObj;
import com.sdyy.common.mongodb.dao.MongoBaseDao;
@Component
public class LicenceMaintMapper extends MongoBaseDao{
}
package com.sdyy.biz.licence.maint.service;
import java.util.List;
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.stereotype.Service;
import com.sdyy.biz.licence.maint.entity.TestObj;
import com.sdyy.biz.licence.maint.mappers.LicenceMaintMapper;
@Service
public class LicenceMaintServiceImpl {
@Autowired
private LicenceMaintMapper LicenceMaintMapper;
public void test(){
Query query=new Query();
Criteria criteria = Criteria.where("site").is("www.runoob.com");
query.addCriteria(criteria);
// query.addCriteria(Criteria.where("site").is("www.runoob.com"));
// Object save = MongoBaseDao.save("aaa");
List find =LicenceMaintMapper.find(query,"test");
/* LicenceMaintMapper.find(query);*/
}
}
https://blog.csdn.net/weixin_41792559/article/details/79575524