Springboot整合Mongodb

一、Springboot整合MongoDB

1、添加依赖
  
   <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-data-mongodbartifactId>
    dependency>

2、添加配置
spring:
  data:
    mongodb:
      host: ${host}
      port: ${port}
      username: ${username} # 用户名
      password: ${password} # 密码
      database: ${databse}
      authenticationDatabase: ${auth_database}# 认证的库名
3、添加配置类
@Configuration
public class MongoDBConfig {

    @Bean // 目的,就是为了移除 _class field 。参考博客 https://blog.csdn.net/bigtree_3721/article/details/82787411
    public MappingMongoConverter mappingMongoConverter(MongoDbFactory factory,
                    MongoMappingContext context, BeanFactory beanFactory) {
        DbRefResolver dbRefResolver = new DefaultDbRefResolver(factory);
        MappingMongoConverter mappingConverter = new MappingMongoConverter(dbRefResolver, context);
        mappingConverter.setCustomConversions(beanFactory.getBean(CustomConversions.class));
        mappingConverter.setTypeMapper(new DefaultMongoTypeMapper(null));
        return mappingConverter;
    }
}
3、创建操作实体
@Data
@Document(collection="tb_mg_book")
public class Book implements Serializable {

	@Id
	private String id;
	private Integer price;
	private String name;
	private String info;
	private String publish;
	private Date createTime;
	private Date updateTime;
} 
5、mongoDB基础方法封装
public abstract class MongoDbDao<T> {

    protected abstract Class<T> getEntityClass();

    @Autowired
    private MongoTemplate mongoTemplate;

    //===================查询方法=====================//
 
    //通过ID查询
    public T queryById(Integer id) {
        Query query = new Query(Criteria.where("_id").is(id));
        return this.mongoTemplate.findOne(query, this.getEntityClass());
    }
	//查询多个
    public List<T> queryList(T object) {
        Query query = getQueryByObject(object);
        return mongoTemplate.find(query, this.getEntityClass());
    }
	//查询一个
    public T queryOne(T object) {
        Query query = getQueryByObject(object);
        return mongoTemplate.findOne(query, this.getEntityClass());
    }
    //查询分页
    public List<T> getPage(T object, int start, int size) {
        Query query = getQueryByObject(object);
        query.skip(start);
        query.limit(size);
        logger.info("-------------->MongoDB queryPage start");
        return this.mongoTemplate.find(query, this.getEntityClass());
    }
    //查询数量
    public Long getCount(T object) {
        Query query = getQueryByObject(object);
        logger.info("-------------->MongoDB Count start");
        return this.mongoTemplate.count(query, this.getEntityClass());
    }
    //======================新增操作=====================//
    //保存
    public void save(T t) {
        this.mongoTemplate.save(t);
    }
    //======================删除=====================//
    //删除
    public int delete(T t) {
        logger.info("-------------->MongoDB delete start");
        return (int) this.mongoTemplate.remove(t).getDeletedCount();
    }
	//根据ID删除
    public void deleteById(Integer id) {
        Criteria criteria = Criteria.where("_id").is(id);
        if (null != criteria) {
            Query query = new Query(criteria);
            T obj = this.mongoTemplate.findOne(query, this.getEntityClass());
            logger.info("-------------->MongoDB deleteById start");
            if (obj != null) {
                this.delete(obj);
            }
        }
    }
	//==============更新操作======================//
    //更新匹配到的第一个
    public void updateFirst(T srcObj, T targetObj){
        Query query = getQueryByObject(srcObj);
        Update update = getUpdateByObject(targetObj);
        logger.info("-------------->MongoDB updateFirst start");
        this.mongoTemplate.updateFirst(query,update,this.getEntityClass());
    }
    // 修改匹配到的所有记录
    public void updateMulti(T srcObj, T targetObj){
        Query query = getQueryByObject(srcObj);
        Update update = getUpdateByObject(targetObj);
        logger.info("-------------->MongoDB updateFirst start");
        this.mongoTemplate.updateMulti(query,update,this.getEntityClass());
    }
 	//修改匹配到的记录,若不存在该记录则进行添加
    public void updateInsert(T srcObj, T targetObj){
        Query query = getQueryByObject(srcObj);
        Update update = getUpdateByObject(targetObj);
        logger.info("-------------->MongoDB updateInsert start");
        this.mongoTemplate.upsert(query,update,this.getEntityClass());
    }

 	//内部方法:将查询条件对象转换为query
    private Query getQueryByObject(T object) {
        Query query = new Query();
        String[] fileds = getFiledName(object);
        Criteria criteria = new Criteria();
        for (int i = 0; i < fileds.length; i++) {
            String filedName = (String) fileds[i];
            Object filedValue = getFieldValueByName(filedName, object);
            if (filedValue != null) {
                criteria.and(filedName).is(filedValue);
            }
        }
        query.addCriteria(criteria);
        return query;
    }

   	//内部方法:将查询条件对象转换为update
    private Update getUpdateByObject(T object) {
        Update update = new Update();
        String[] fileds = getFiledName(object);
        for (int i = 0; i < fileds.length; i++) {
            String filedName = (String) fileds[i];
            Object filedValue =getFieldValueByName(filedName, object);
            if (filedValue != null) {
                update.set(filedName, filedValue);
            }
        }
        return update;
    }

   //内部方法:获取对象属性返回字符串数组
    private static String[] getFiledName(Object o) {
        Field[] fields = o.getClass().getDeclaredFields();
        String[] fieldNames = new String[fields.length];

        for (int i = 0; i < fields.length; ++i) {
            fieldNames[i] = fields[i].getName();
        }

        return fieldNames;
    }
	//内部方法:根据属性获取对象属性值
    private static Object getFieldValueByName(String fieldName, Object o) {
        try {
            String e = fieldName.substring(0, 1).toUpperCase();
            String getter = "get" + e + fieldName.substring(1);
            Method method = o.getClass().getMethod(getter, new Class[0]);
            return method.invoke(o, new Object[0]);
        } catch (Exception var6) {
            return null;
        }
    }
}

  • 参照:http://www.ityouknow.com/springboot/2017/05/08/spring-boot-mongodb.html
  • https://blog.csdn.net/qq_22136439/article/details/113557020?spm=1001.2014.3001.5501
  • 结合目前的企业实践

你可能感兴趣的:(spring,boot,mongodb,后端)