• MongoDB入门(5)- 我们自己封装的MongoDB-Java版本


    用法

    实体定义

    package com.wisdombud.mongotool;
    
    import java.io.Serializable;
    import java.util.Date;
    import java.util.List;
    
    import org.springframework.data.mongodb.core.mapping.Document;
    
    @Document(collection = "Project")
    public class Project extends MongoDbEntity implements Serializable {
    
    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 1L;
    	private String ProjectId;
    	private String weituodanwei;
    	private String weituodanweidizhi;
    	private String post;
    	private String yangpinzhizaodanwei;
    	private String zhizaodanweidizhi;
    	private String phone;
    	private String contact;
    	private String yangpinjiazhi;
    
    	public String getProjectId() {
    		return ProjectId;
    	}
    
    	public void setProjectId(String projectId) {
    		ProjectId = projectId;
    	}
    
    	public String getWeituodanwei() {
    		return weituodanwei;
    	}
    
    	public void setWeituodanwei(String weituodanwei) {
    		this.weituodanwei = weituodanwei;
    	}
    
    	public String getWeituodanweidizhi() {
    		return weituodanweidizhi;
    	}
    
    	public void setWeituodanweidizhi(String weituodanweidizhi) {
    		this.weituodanweidizhi = weituodanweidizhi;
    	}
    
    	public String getPost() {
    		return post;
    	}
    
    	public void setPost(String post) {
    		this.post = post;
    	}
    
    	public String getYangpinzhizaodanwei() {
    		return yangpinzhizaodanwei;
    	}
    
    	public void setYangpinzhizaodanwei(String yangpinzhizaodanwei) {
    		this.yangpinzhizaodanwei = yangpinzhizaodanwei;
    	}
    
    	public String getZhizaodanweidizhi() {
    		return zhizaodanweidizhi;
    	}
    
    	public void setZhizaodanweidizhi(String zhizaodanweidizhi) {
    		this.zhizaodanweidizhi = zhizaodanweidizhi;
    	}
    
    	public String getPhone() {
    		return phone;
    	}
    
    	public void setPhone(String phone) {
    		this.phone = phone;
    	}
    
    	public String getContact() {
    		return contact;
    	}
    
    	public void setContact(String contact) {
    		this.contact = contact;
    	}
    
    	public String getYangpinjiazhi() {
    		return yangpinjiazhi;
    	}
    
    	public void setYangpinjiazhi(String yangpinjiazhi) {
    		this.yangpinjiazhi = yangpinjiazhi;
    	}
    
    	public String getShenqingleixing() {
    		return shenqingleixing;
    	}
    
    	public void setShenqingleixing(String shenqingleixing) {
    		this.shenqingleixing = shenqingleixing;
    	}
    
    	public String getYangpinmingcheng() {
    		return yangpinmingcheng;
    	}
    
    	public void setYangpinmingcheng(String yangpinmingcheng) {
    		this.yangpinmingcheng = yangpinmingcheng;
    	}
    
    	public String getXinghao() {
    		return xinghao;
    	}
    
    	public void setXinghao(String xinghao) {
    		this.xinghao = xinghao;
    	}
    
    	public String getNumber() {
    		return number;
    	}
    
    	public void setNumber(String number) {
    		this.number = number;
    	}
    
    	public String getJianceyiju() {
    		return jianceyiju;
    	}
    
    	public void setJianceyiju(String jianceyiju) {
    		this.jianceyiju = jianceyiju;
    	}
    
    	public List<String> getJiancexiangmu() {
    		return jiancexiangmu;
    	}
    
    	public void setJiancexiangmu(List<String> jiancexiangmu) {
    		this.jiancexiangmu = jiancexiangmu;
    	}
    
    	public String getYangpinzhuangkuang() {
    		return yangpinzhuangkuang;
    	}
    
    	public void setYangpinzhuangkuang(String yangpinzhuangkuang) {
    		this.yangpinzhuangkuang = yangpinzhuangkuang;
    	}
    
    	public String getYangpinxuhao() {
    		return yangpinxuhao;
    	}
    
    	public void setYangpinxuhao(String yangpinxuhao) {
    		this.yangpinxuhao = yangpinxuhao;
    	}
    
    	public String getYangpinfujian() {
    		return yangpinfujian;
    	}
    
    	public void setYangpinfujian(String yangpinfujian) {
    		this.yangpinfujian = yangpinfujian;
    	}
    
    	public String getYangpintijiaofangshi() {
    		return yangpintijiaofangshi;
    	}
    
    	public void setYangpintijiaofangshi(String yangpintijiaofangshi) {
    		this.yangpintijiaofangshi = yangpintijiaofangshi;
    	}
    
    	public String getYangpinbaogaotijiaofangshi() {
    		return yangpinbaogaotijiaofangshi;
    	}
    
    	public void setYangpinbaogaotijiaofangshi(String yangpinbaogaotijiaofangshi) {
    		this.yangpinbaogaotijiaofangshi = yangpinbaogaotijiaofangshi;
    	}
    
    	public String getYangpinchuzhifangshi() {
    		return yangpinchuzhifangshi;
    	}
    
    	public void setYangpinchuzhifangshi(String yangpinchuzhifangshi) {
    		this.yangpinchuzhifangshi = yangpinchuzhifangshi;
    	}
    
    	public Date getCreateDay() {
    		return CreateDay;
    	}
    
    	public void setCreateDay(Date createDay) {
    		CreateDay = createDay;
    	}
    
    	private String shenqingleixing;
    	private String yangpinmingcheng;
    	private String xinghao;
    	private String number;
    	private String jianceyiju;
    	private List<String> jiancexiangmu;
    	private String yangpinzhuangkuang;
    	private String yangpinxuhao;
    	private String yangpinfujian;
    	private String yangpintijiaofangshi;
    	private String yangpinbaogaotijiaofangshi;
    	private String yangpinchuzhifangshi;
    	private Date CreateDay;
    
    }
    
    

    DAO实现

    package com.wisdombud.mongotool;
    
    import org.springframework.data.mongodb.core.MongoOperations;
    
    public class ProjectDaoImpl extends SimpleMongoDaoImpl<Project, String> implements ProjectDao {
    
    	public ProjectDaoImpl(MongoOperations mongoOper) {
    		super(mongoOper);
    	}
    
    }
    
    

    核心源码

    package com.wisdombud.mongotool;
    
    
    import java.io.Serializable;
    import java.lang.reflect.Field;
    import java.util.Collection;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    import org.apache.commons.lang.ArrayUtils;
    import org.bson.types.ObjectId;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.data.domain.Sort;
    import org.springframework.data.domain.Sort.Order;
    import org.springframework.data.mongodb.core.MongoOperations;
    import org.springframework.data.mongodb.core.query.Criteria;
    import org.springframework.data.mongodb.core.query.Query;
    
    import common.toolkit.java.entity.PageEntity;
    import common.toolkit.java.orm.hibernate.GeneralQuery;
    import common.toolkit.java.util.ReflectUtils;
    
    public class SimpleMongoDaoImpl<T, PK extends Serializable> implements SimpleMongoDao<T, PK> {
        @Autowired
        protected MongoOperations mongoOper;
        protected Class<T>        entityClazz;
        /**
         * 字符串分隔的标志符号,现在用:表示,在关联查询的时候用。
         ***/
        private final String      splitMarker = "::";
    
    
    
        public SimpleMongoDaoImpl(MongoOperations mongoOper) {
            this.mongoOper = mongoOper;
            this.entityClazz = ReflectUtils.getSuperClassGenricType(getClass());
        }
    
        @Override
        public PK save(T entity) {
        	return null;
        }
    
        @Override
        public void update(T entity) {
        	 mongoOper.save(entity);
        }
    
        @Override
        public void saveOrUpdate(T entity) {
            mongoOper.save(entity);
        }
    
        @Override
        public void saveOrUpdate(Collection<T> entities) {
            for (T entity : entities) {
                mongoOper.save(entity);
            }
        }
    
        @Override
        public void delete(T entity) {
            mongoOper.remove(entity);
        }
    
        @Override
        public void deleteAll(Collection<T> entities) {
            for (T entity : entities) {
                mongoOper.remove(entity);
            }
        }
    
        @Override
        public void deleteById(PK id) {
            mongoOper.remove(new Query(Criteria.where("_id").is(id)), entityClazz);
        }
    
        @Override
        public T get(PK id) {
            return mongoOper.findById(id, entityClazz);
        }
    
        @Override
        public List<T> getAll() {
            return this.mongoOper.findAll(entityClazz);
        }
    
        @Override
        public T load(PK id) {
    
            // TODO Auto-generated method stub
            return null;
        }
    
        @Override
        public void refresh(T entity) {
    
            // TODO Auto-generated method stub
    
        }
    
        @Override
        public void merge(T entity) {
    
            // TODO Auto-generated method stub
    
        }
    
        @Override
        public void merge(String entityName, T entity) {
    
            // TODO Auto-generated method stub
    
        }
    
        @Override
        public void evict(T entity) {
    
            // TODO Auto-generated method stub
    
        }
    
        @Override
        public boolean contains(Object entity) {
    
            // TODO Auto-generated method stub
            return false;
        }
    
        @Override
        public List<T> findBy(String propertyName, Object value) {
            HashMap<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put(propertyName, value);
            return this.findBy(paramMap, null);
        }
    
        @Override
        public List<T> findBy(Map<String, Object> paramMap, List<Order> orderList) {
            Query query = this.buildQuery(paramMap, orderList);
            return mongoOper.find(query, entityClazz);
        }
    
        @Override
        public T findUniqueBy(String propertyName, Object value) {
            HashMap<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put(propertyName, value);
            Query query = this.buildQuery(paramMap, null);
            return mongoOper.findOne(query, entityClazz);
        }
    
        @Override
        public T findUniqueBy(Map<String, Object> paramMap, List<Order> orderList) {
            Query query = this.buildQuery(paramMap, orderList);
            return mongoOper.findOne(query, entityClazz);
        }
    
        @Override
        public void pageList(Map<String, Object> paramMap, List<Order> orderList, PageEntity<T> pageEntity) {
            Query query = this.buildQuery(paramMap, orderList);
            pageEntity.setTotalResults(mongoOper.count(query, entityClazz));// 总记录数
            pageEntity.setTotalPages();// 总页数
            query.skip(pageEntity.getStart());
            query.limit(pageEntity.getPageSize());
            pageEntity.setResults(mongoOper.find(query, entityClazz));// 分页数据
            pageEntity.setCurrentPageLength(pageEntity.getResults().size());// 当前页面记录数
        }
    
        public Class<T> getEntityClazz() {
            return entityClazz;
        }
    
        public void setEntityClazz(Class<T> entityClazz) {
            this.entityClazz = entityClazz;
        }
    
        protected void buildQuery(String key, Object value, Query query) {
            // 如果为数字
            if (key.contains("_id")) {
                query.addCriteria(Criteria.where(key).is(new ObjectId(value.toString())));
            } else {
                if (value instanceof Integer || value instanceof Float || value instanceof Double
                    || value instanceof Boolean) {
                    query.addCriteria(Criteria.where(key).is(value));
                } else {
                    // 字符串 模糊查询
                    // i为查询大小写不敏感
                    query.addCriteria(Criteria.where(key).regex(value.toString(), "i"));
                }
            }
        }
    
        protected Query buildQuery(Map<String, Object> paramMap, List<Order> orderList) {
            Query query = new Query();
            if (paramMap != null && paramMap.size() > 0) {
                for (String key : paramMap.keySet()) {
                    Object value = paramMap.get(key);
                    if (key.contains(this.splitMarker)) {// 处理关联查询的情况
                        String[] arr = key.split(this.splitMarker);
                        if (arr.length != 2) {
                            continue;
                        }
                        String p1 = arr[0];
                        String p2 = arr[1];
    
                        Class<T> clazz = ReflectUtils.getSuperClassGenricType(getClass());
    
                        Field[] fs = this.getAllFields(clazz);
                        // ReflectUtils.getAllFields(clazz);
    
                        Class<?> clazz1 = null;
                        for (Field f : fs) {
                            if (f.getName().equals(p1)) {
                                clazz1 = f.getType();
                                break;
                            }
                        }
                        Query query0 = new Query();
                        this.buildQuery(p2, value, query0);
                        query.addCriteria(Criteria.where(p1).in(mongoOper.find(query0, clazz1)));
    
                    } else {
                        this.buildQuery(key, value, query);
                    }
                }
            }
    
            if (orderList != null && orderList.size() > 0) {
                Sort sort = new Sort(orderList);
                query.with(sort);
            }
    
            return query;
        }
    
        private Field[] getAllFields(Class<? super T> clazz) {
    
            Class<?> originClazz = clazz;
            Field[] resultField = clazz.getDeclaredFields();
    
            for (; clazz != Object.class; clazz = clazz.getSuperclass()) {
                if (clazz == originClazz) {
                    continue;
                }
                try {
                    Field[] superFields = clazz.getDeclaredFields();
                    resultField = (Field[]) ArrayUtils.addAll(resultField, superFields);
                } catch (Exception e) {
                    System.out.println("error");
                }
            }
    
            return resultField;
        }
    
        @Override
        public List<T> findBy(Map<String, Object> paramsMap) {
            // TODO Auto-generated method stub
            return null;
        }
    
        @Override
        public GeneralQuery<T> createGeneralQuery() {
            // TODO Auto-generated method stub
            return null;
        }
    }
    
    
  • 相关阅读:
    四种读写方案IO流 (JAVA)
    如何保证ArrayList线程安全
    异常总结 (经典)
    JAVA反射机制
    移位运算符(JAVA)
    return和finally的执行顺序
    适配器模式(接口)
    2020年大厂Java面试题集锦,干货集锦,快来集合了!
    资深架构师解析springcloud分布式微服务的实现
    HTTP最全最新资料大全
  • 原文地址:https://www.cnblogs.com/wardensky/p/5799286.html
Copyright © 2020-2023  润新知