虽然不用了,但是记录下吧,一些思想还是要的
public class BaseMongoDao { private static MongoClient mongoClient; private static MongoConfig config; private static MongoDatabase mongo; private String colName; public static void init(MongoConfig initconfig){ config = initconfig; MongoClientOptions options = MongoClientOptions.builder() .connectionsPerHost(config.getConnectionsPerHost()) .maxWaitTime(config.getMaxWaitTime()) .socketTimeout(config.getSocketTimeout()) .maxConnectionLifeTime(config.getMaxConnectionLifeTime()) .connectTimeout(config.getConnectTimeout()).build(); ServerAddress serverAddress = new ServerAddress(config.getDBUrl(), config.getDBPort()); List<ServerAddress> addrs = new ArrayList<ServerAddress>(); addrs.add(serverAddress); List<MongoCredential> cres = new ArrayList<MongoCredential>(); MongoCredential credential = MongoCredential.createScramSha1Credential( config.getDBUser() ,config.getDBName() ,config.getDBpwd().toCharArray()); cres.add(credential); mongoClient = new MongoClient(addrs, cres, options); mongo = mongoClient.getDatabase(config.getDBName()); } public BaseMongoDao(String colName) { this.colName = colName; } private MongoCollection<Document> thisCollection() throws DAOException { if(config==null){ throw new DAOException("Dao Config no init error"); } return mongo.getCollection(colName); } /** * 列表查询 * @param query 查询 * @param orderKey 排序key * @param up 升序 asc true 降序 desc false * @return * @throws DAOException */ public <Q> List<Q> queryByCondition(BaseQuery<Q> query,String orderKey,boolean up) throws DAOException { orderKey = StringUtil.isBlank(orderKey)?"_id":orderKey; Q record = query.getQuery(); BasicDBObject cond = getCondition(record); FindIterable<Document> findIterable; if (query.getStart() != null && query.getRows() != null) findIterable = thisCollection().find(cond) .sort(new BasicDBObject(orderKey, up ? 1 : -1)) .skip((query.getStart() - 1) * query.getRows()) .limit(query.getRows()); else findIterable = thisCollection().find(cond) .sort(new BasicDBObject(orderKey, up ? 1 : -1)); MongoCursor<Document> iterator = findIterable.iterator(); List<Q> result = new ArrayList<Q>(); while (iterator.hasNext()) { Document document = iterator.next(); result.add((Q) parseToObject(document, record.getClass())); } iterator.close(); return result; } /** * 数量查询 * @param query * @return * @throws DAOException */ public <Q> Integer queryCoditionCount(BaseQuery<Q> query) throws DAOException { Q record = query.getQuery(); BasicDBObject cond = getCondition(record); return (int) thisCollection().count(cond); } /** * 插入数据 * @param record * @return */ public <Q> boolean insertOne(Q record) { BasicDBObject cond = getCondition(record); try { thisCollection().insertOne(new Document(cond)); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 批量插入 * @param records * @return */ public <Q> boolean insertList(List<Q> records) { try { List<Document> list = new ArrayList<Document>(records.size()); for (Q record : records) { list.add(new Document(getCondition(record))); } thisCollection().insertMany(list); return true; }catch (Exception e) { e.printStackTrace(); return false; } } /** * 条件删除 * @param key * @param val * @return */ public boolean deleteByKey(String key,Object val) { try { if (key == null || val == null) return false; thisCollection().deleteOne(new BasicDBObject(key,val)); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 多key值删除 * @param key * @param vals * @return */ public boolean deleteByKeys(String key ,List<Object> vals) { BasicDBObject cond = new BasicDBObject(key,new BasicDBObject("$in",vals.toArray())); try { thisCollection().deleteMany(cond); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 通过给定key更改 * @param record * @param <Q> * @throws DAOException */ public <Q> void updateByKey(String key,Q record) throws DAOException { BasicDBObject cond = getCondition(record); BasicDBObject update = new BasicDBObject("$set",cond); BasicDBObject query = new BasicDBObject(key,cond.get(key)); thisCollection().updateOne(query,update); } /** * * @param key * @param record * @throws DAOException */ public <Q> void upsertByKey(String key,Q record) throws DAOException { BasicDBObject cond = getCondition(record); BasicDBObject update = new BasicDBObject("$set",cond); BasicDBObject query = new BasicDBObject(key,cond.get(key)); UpdateOptions options = new UpdateOptions(); options.upsert(true); thisCollection().updateOne(query, update, options); } /** * 通过反射获取非空字段信息 * @param record * @param <Q> * @return */ private <Q> BasicDBObject getCondition(Q record) { BasicDBObject cond = new BasicDBObject(); Class clazz = record.getClass(); Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { try { field.setAccessible(true); Object value = field.get(record); if (value != null) cond.put(field.getName(), value); } catch (IllegalAccessException e) { e.printStackTrace(); } } return cond; } /** * 将结果转化为自定义对象 * @param document * @param target * @param <Q> * @return */ private <Q> Q parseToObject(Document document, Class<Q> target) { try { Q result = target.newInstance(); Field[] fields = target.getDeclaredFields(); for (Field f : fields) { f.setAccessible(true); Object value = document.get(f.getName()); if (value == null) continue; else if (f.getType() == Integer.class) f.set(result, ((Number) value).intValue()); else if (f.getType() == Long.class) f.set(result, ((Number) value).longValue()); else if(isBaseType(f.getType().toString())) f.set(result, value); else f.set(result, document.get(f.getName(), f.getType())); } return result; } catch (IllegalAccessException e) { e.printStackTrace(); return null; } catch (InstantiationException e) { e.printStackTrace(); return null; } } /** * 查找顶针 * @return default 0 * @throws DAOException */ private Object getTop(String key) throws DAOException { FindIterable<Document> it = thisCollection().find().sort(new BasicDBObject(key,-1)); if(it.first()==null){ return 0; }else{ return it.first().get(key); } } public <Q> List<Q> queryByConditionRange(BaseQuery<Q> query,String orderKey,boolean up,String rangeKey,Number gte,Number lte) throws DAOException { orderKey = StringUtil.isBlank(orderKey)?"_id":orderKey; Q record = query.getQuery(); BasicDBObject cond = getCondition(record); cond.put(rangeKey, new BasicDBObject("$gte", gte).append("$lte", lte)); FindIterable<Document> findIterable; if (query.getStart() != null && query.getRows() != null) findIterable = thisCollection().find(cond) .sort(new BasicDBObject(orderKey, up ? 1 : -1)) .skip((query.getStart() - 1) * query.getRows()) .limit(query.getRows()); else findIterable = thisCollection().find(cond) .sort(new BasicDBObject(orderKey, up ? 1 : -1)); MongoCursor<Document> iterator = findIterable.iterator(); List<Q> result = new ArrayList<Q>(); while (iterator.hasNext()) { Document document = iterator.next(); result.add((Q) parseToObject(document, record.getClass())); } iterator.close(); return result; } /** * 判断object是否为基本类型 * @param object * @return */ public static boolean isBaseType(String className) { if (className.equals("int") || className.equals("byte") || className.equals("long") || className.equals("double") || className.equals("float") || className.equals("char") || className.equals("short") || className.equals("boolean")) { return true; } return false; }
public class BaseQuery<Q> { private Integer start; private Integer rows; private Q query; public BaseQuery(Class clazz) { try { this.query = (Q) clazz.newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } public Integer getStart() { return start; } public void setStart(Integer start) { this.start = start; } public Integer getRows() { return rows; } public void setRows(Integer rows) { this.rows = rows; } public Q getQuery() { return query; } public void setQuery(Q query) { this.query = query; } }
public class MongoConfig { private int DBPort; private String DBUrl; private String DBName; private String DBUser; private String DBpwd; private int connectionsPerHost; private int maxWaitTime; private int socketTimeout; private int maxConnectionLifeTime; private int connectTimeout; public int getDBPort() { return DBPort; } public void setDBPort(int dBPort) { DBPort = dBPort; } public String getDBUrl() { return DBUrl; } public void setDBUrl(String dBUrl) { DBUrl = dBUrl; } public String getDBName() { return DBName; } public void setDBName(String dBName) { DBName = dBName; } public String getDBUser() { return DBUser; } public void setDBUser(String dBUser) { DBUser = dBUser; } public String getDBpwd() { return DBpwd; } public void setDBpwd(String dBpwd) { DBpwd = dBpwd; } public int getConnectionsPerHost() { return connectionsPerHost; } public void setConnectionsPerHost(int connectionsPerHost) { this.connectionsPerHost = connectionsPerHost; } public int getMaxWaitTime() { return maxWaitTime; } public void setMaxWaitTime(int maxWaitTime) { this.maxWaitTime = maxWaitTime; } public int getSocketTimeout() { return socketTimeout; } public void setSocketTimeout(int socketTimeout) { this.socketTimeout = socketTimeout; } public int getMaxConnectionLifeTime() { return maxConnectionLifeTime; } public void setMaxConnectionLifeTime(int maxConnectionLifeTime) { this.maxConnectionLifeTime = maxConnectionLifeTime; } public int getConnectTimeout() { return connectTimeout; } public void setConnectTimeout(int connectTimeout) { this.connectTimeout = connectTimeout; } }
乐享:知识积累,快乐无限。