• MongoTemplate 操作 mongodb


    1. 增加依赖

            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-mongodb</artifactId>
                <version>1.5.2.RELEASE</version>
            </dependency>

    2.增加配置

    spring.data.mongodb.database=test
    spring.data.mongodb.uri=mongodb://user:password@192.168.1.2:27017/admin

     3.Operator类

    import com.google.common.collect.ImmutableMap;
    
    import com.g2.order.server.business.vo.common.PagedResult;
    import com.mongodb.WriteResult;
    
    import org.bson.types.ObjectId;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.data.annotation.Id;
    import org.springframework.data.mongodb.core.FindAndModifyOptions;
    import org.springframework.data.mongodb.core.MongoTemplate;
    import org.springframework.data.mongodb.core.mapping.Document;
    import org.springframework.data.mongodb.core.query.Criteria;
    import org.springframework.data.mongodb.core.query.Update;
    import org.springframework.stereotype.Component;
    import org.springframework.util.Assert;
    import org.springframework.util.CollectionUtils;
    import org.springframework.data.mongodb.core.query.Query;
    import org.springframework.data.domain.Sort;
    
    import java.util.List;
    import java.util.Map;
    
    import lombok.Data;
    
    /**
     * 操作类.
     */
    public class MongoDbOperator<T> {
        private MongoTemplate mongoTemplate;
    
        private Class<T> tClass;
    
        public MongoDbOperator(MongoTemplate mongoTemplate, Class<T> classz) {
            this.mongoTemplate = mongoTemplate;
            this.tClass = classz;
        }
    
    
        public T getOne(ObjectId id) {
            return mongoTemplate.findById(id, tClass);
        }
    
        public T getOne(String id) {
            return getOne(new ObjectId(id));
        }
    
        public T getOne(Map<String, Object> filter) {
            Assert.notNull(filter, "过滤条件不能为空");
            Query queryFilter = getQueryFilter(filter);
    
            return mongoTemplate.findOne(queryFilter, tClass);
        }
    
        /**
         * 获取单个model
         *
         * @param filter 过滤条件
         * @param sort   Sort theSort = new Sort(Sort.Direction.ASC, "_id");
         */
        public T getOne(Map<String, Object> filter, Sort sort) {
            Query queryFilter = getQueryFilter(filter);
            queryFilter = queryFilter.with(sort);
    
            return mongoTemplate.findOne(queryFilter, tClass);
        }
    
        /**
         * 按访问时间倒序排列
         *
         * @param filter 过滤条件
         * @param sort   排序条件
         * @param limit  前几个(0:不限制)
         */
        public List<T> list(Map<String, Object> filter, Sort sort, int limit) {
            Query queryFilter = getQueryFilter(filter);
            if (sort != null) {
                queryFilter = queryFilter.with(sort);
            }
            if (limit > 0) {
                queryFilter = queryFilter.limit(limit);
            }
    
            return mongoTemplate.find(queryFilter, tClass);
        }
    
        /**
         * 按访问时间倒序排列
         *
         * @param filter 过滤条件
         */
        public long count(Map<String, Object> filter) {
            Query queryFilter = getQueryFilter(filter);
    
            return mongoTemplate.count(queryFilter, tClass);
        }
    
        /**
         * 分页查询
         *
         * @param filter    过滤条件
         * @param sort      排序条件
         * @param pageIndex 第几页
         * @param pageSize  每页大小
         */
        public PagedResult<T> pagedList(Map<String, Object> filter, Sort sort, int pageIndex, int pageSize) {
            Query queryFilter = getQueryFilter(filter);
            long count = count(queryFilter);
            if (sort != null) {
                queryFilter = queryFilter.with(sort);
            }
            queryFilter = queryFilter.skip((pageIndex - 1) * pageSize).limit(pageSize);
            List<T> subItems = mongoTemplate.find(queryFilter, tClass);
    
            return new PagedResult<>(subItems, pageIndex, pageSize, (int) count);
        }
    
    
        /**
         * 按访问时间倒序排列
         *
         * @param filter 过滤条件
         */
        public List<T> list(Map<String, Object> filter) {
            return list(filter, null, 0);
        }
    
    
        /**
         * 插入新数据
         * 返回的id在obj中赋值
         */
        public void insert(T obj) {
            mongoTemplate.insert(obj);
        }
    
        public int updateOne(String id, Map<String, Object> filedValues) {
            return updateOne(new ObjectId(id), filedValues);
        }
    
        public int updateOne(ObjectId id, Map<String, Object> filedValues) {
            Query queryFilter = getQueryFilter(id);
    
            return updateImpl(queryFilter, filedValues);
        }
    
        public int update(Map<String, Object> filter, Map<String, Object> filedValues) {
            Query queryFilter = getQueryFilter(filter);
    
            return updateImpl(queryFilter, filedValues);
        }
    
        public boolean exists(Map<String, Object> filter) {
            return getOne(filter) != null;
        }
    
        /**
         * 删除
         *
         * @param id _id
         */
        public int delete(String id) {
            Query queryFilter = getQueryFilter(new ObjectId(id));
    
            return delete(queryFilter);
        }
    
        /**
         * 删除
         *
         * @param id _id
         */
        public int delete(ObjectId id) {
            Query queryFilter = getQueryFilter(id);
    
            return delete(queryFilter);
        }
    
        /**
         * 删除
         *
         * @param filter 用户Id
         */
        public int delete(Map<String, Object> filter) {
            Query queryFilter = getQueryFilter(filter);
    
            return delete(queryFilter);
        }
    
        /**
         * 软删除
         *
         * @param filter 用户Id
         */
        public int softDelete(Map<String, Object> filter) {
            Query queryFilter = getQueryFilter(filter);
            WriteResult result = mongoTemplate.updateMulti(queryFilter, Update.update("isDel", 1), tClass);
    
            return result.getN();
        }
    
        /**
         * 根据当前表名获取自增id
         *
         * @param collectionName 表名
         * @return 自增id
         */
        public int getNextSequence() {
            String collectionName = mongoTemplate.getCollectionName(tClass);
            Query query = new Query(Criteria.where("_id").is(collectionName));
            Update update = new Update();
            update.inc("seq", 1);
    
            FindAndModifyOptions options = new FindAndModifyOptions();
            options.upsert(true);
            options.returnNew(true);
    
            MongoSequence item = mongoTemplate.findAndModify(query, update, options, MongoSequence.class);
    
            return item.getSeq();
        }
    
        private long count(Query queryFilter) {
            return mongoTemplate.count(queryFilter, tClass);
        }
    
        /**
         * 删除
         *
         * @param queryFilter 用户Id
         */
        private int delete(Query queryFilter) {
            return mongoTemplate.remove(queryFilter, tClass).getN();
        }
    
        private int updateImpl(Query queryFilter, Map<String, Object> filedValues) {
            Update updateOperations = new Update();
            for (Map.Entry<String, Object> entry : filedValues.entrySet()) {
                updateOperations.set(entry.getKey(), entry.getValue());
            }
            WriteResult writeResult = mongoTemplate.updateMulti(queryFilter, updateOperations, tClass);
            return writeResult.getN();
        }
    
        private Query getQueryFilter(ObjectId id) {
            return getQueryFilter(ImmutableMap.of("_id", id));
        }
    
        private Query getQueryFilter(Map<String, Object> filter) {
            Query query = new Query();
            if (CollectionUtils.isEmpty(filter)) {
                return query;
            }
            Criteria criteria = new Criteria();
            boolean w = false;
            for (Map.Entry<String, Object> entry : filter.entrySet()) {
                if (!w) {
                    criteria = (Criteria.where(entry.getKey()).is(entry.getValue()));
                    w = true;
                } else {
                    criteria = criteria.and(entry.getKey()).is(entry.getValue());
                }
            }
            query.addCriteria(criteria);
            return query;
        }
    
        private Update getUpdateOperations(Map<String, Object> filedValues) {
            Update updateOperations = new Update();
            updateOperations.inc("version", 1);
            updateOperations.set("lastModifyTime", System.currentTimeMillis());
            for (Map.Entry<String, Object> entry : filedValues.entrySet()) {
                updateOperations.set(entry.getKey(), entry.getValue());
            }
    
            return updateOperations;
        }
    
        private Update getSoftDeleteOperations() {
            return getUpdateOperations(ImmutableMap.of("deleted", true));
        }
    
        /**
         * 自增序列维护表
         */
        @Data
        @Document(collection = "___MongoSequence___")
        private static class MongoSequence {
            /**
             * 表名做主键
             */
            @Id
            private String id;
    
            /**
             * 对应表的最新自增id
             */
            private int seq;
        }
    }

    4.mongodb不保存"_class"字段的配置

    import org.springframework.beans.factory.BeanFactory;
    import org.springframework.beans.factory.NoSuchBeanDefinitionException;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.data.mongodb.MongoDbFactory;
    import org.springframework.data.mongodb.core.convert.CustomConversions;
    import org.springframework.data.mongodb.core.convert.DbRefResolver;
    import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver;
    import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
    import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
    import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
    
    /**
     * 覆盖原有的Convert,新的convert不保存_class字段
     */
    @Configuration
    public class SpringMongodbTemplateConfig {
        @Bean
        public MappingMongoConverter mappingMongoConverter(MongoDbFactory factory, MongoMappingContext context,
                BeanFactory beanFactory) {
            DbRefResolver dbRefResolver = new DefaultDbRefResolver(factory);
            MappingMongoConverter mappingConverter = new MappingMongoConverter(dbRefResolver, context);
            try {
                mappingConverter.setCustomConversions(beanFactory.getBean(CustomConversions.class));
            } catch (NoSuchBeanDefinitionException ignore) {
            }
    
            // 不保存 _class 到 mongo
            mappingConverter.setTypeMapper(new DefaultMongoTypeMapper(null));
    
            return mappingConverter;
        }
    }

    5.测试model类

    @Document(collection = "login_log")
    @Data
    public class LoginLog {
        @Id
        private String id;
        private String customerId;
     private long lastLoginTime;
    }

     6.接口

    import com.google.common.collect.ImmutableMap;
    import com.g2.order.server.business.MongoDbOperator;
    import com.g2.order.server.business.vo.LoginLog;
    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.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RestController;
    import java.util.List;
    import javax.annotation.PostConstruct;
    import io.swagger.annotations.Api;
    import io.swagger.annotations.ApiOperation;
    import lombok.extern.slf4j.Slf4j;
    
    
    @Api(value = "MongodbController", description = "登陆日志接口")
    @RestController
    @RequestMapping("/loginLog")
    @Slf4j
    public class MongodbController {
        @Autowired
        private MongoTemplate template;
    
        private MongoDbOperator<LoginLog> mongoDbOperator;
    
        @PostConstruct
        void init() {
            mongoDbOperator = new MongoDbOperator<>(template, LoginLog.class);
        }
    
        /**
         * 使用MongoTemplate查询数据
         */
        @ApiOperation(value = "获取用户的登陆日志", notes = "获取用户的登陆日志")
        @RequestMapping(value = "/list",
                method = RequestMethod.GET)
        public String list(String key) {
            Query query = new Query();
            query.addCriteria(Criteria.where("customerId").is(Integer.parseInt(key)));
            List<LoginLog> clientDevices = template.find(query, LoginLog.class);
    
            return clientDevices.toString();
        }
    
        @ApiOperation(value = "获取用户的登陆日志2", notes = "获取用户的登陆日志2")
        @RequestMapping(value = "/list2",
                method = RequestMethod.GET)
        public String list2(String key) {
            LoginLog model = mongoDbOperator.getOne(ImmutableMap.of("customerId", Integer.parseInt(key)));
    
            return model.toString();
        }
    
        @ApiOperation(value = "新增用户登录日志", notes = "新增用户登录日志")
        @RequestMapping(value = "/add",
                method = RequestMethod.GET)
        public String add(String customerId) {
            LoginLog model = new LoginLog();
            model.setId(mongoDbOperator.getNextSequence());
            model.setCustomerId(customerId);
            model.setLastLoginTime(System.currentTimeMillis());
            mongoDbOperator.insert(model);
    
            return model.toString();
        }
    }
  • 相关阅读:
    js检验文件格式
    java判空工具类
    $(document).ready() 是个什么函数?为什么要用它?
    Maven 手动添加jar
    java深克隆
    cors跨域详解
    常见异常类总结
    Spring事务回滚机制
    Java获取13位毫秒级时间戳
    JSON 字符串转换为 Map
  • 原文地址:https://www.cnblogs.com/zhshlimi/p/12177538.html
Copyright © 2020-2023  润新知