zoukankan      html  css  js  c++  java
  • Mongodb总结3-稍微封装一下

      上次发表的2,纯粹是Demo,演示API的用法。

      今天,稍微封装了下,看得更清楚。

     考虑到不容易做得很有通用性,所以封装的一般,换种场景需要直接修改代码,但是有一部分是可以复用的。


    最近项目,很可能只需要4个接口,增加、修改、单个查询、批量查询,所以只封装了4个接口的用法。


    package mongodb;
    
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Date;
    import java.util.List;
    
    import com.mongodb.BasicDBList;
    import com.mongodb.BasicDBObject;
    import com.mongodb.DB;
    import com.mongodb.DBCollection;
    import com.mongodb.DBCursor;
    import com.mongodb.DBObject;
    import com.mongodb.Mongo;
    
    public class MongoDBDemoAdvance {
    
    	public static final String TITLE = "title";
    	public static final String CONTENT = "content";
    	public static final String AUTHOR = "author";
    	public static final String DATE = "date";
    	public static final String ID = "id";
    
    	//构造1个文章、修改之后再存、2个查询
    	public static void main(String[] args) {
    
    		Mongo mongo = MongoUtil.mongo();
    		DB db = mongo.getDB("blog");
    
    		Article article = buildArticle();
    		DBCollection articleCollection = add(db, article);
    
    		article.setId(2L);
    		DBObject object2 = articleToObject2(article);
    		articleCollection.insert(object2);
    
    		Long id = 1L;
    		Article articleBefore = findById(articleCollection, id);
    		if (articleBefore != null) {
    			System.out.println("刚刚新增的文章=" + articleBefore);
    		}
    
    		articleBefore.setTitle("标题被修改啦");
    		update(articleCollection, articleBefore);
    		Article articleAfter = findById(articleCollection, id);
    		if (articleAfter != null) {
    			System.out.println("修改后的文章=" + articleAfter);
    		}
    
    		List idList = Arrays.asList(1L, 2L);
    		List<Article> articleList = findByIdList(articleCollection, idList);
    		if (articleList != null) {
    			for (Article a : articleList) {
    				System.out.println(a);
    			}
    		}
    
    		BasicDBObject removeAll = new BasicDBObject();
    		articleCollection.remove(removeAll);
    	}
    
    	//增加
    	public static DBCollection add(DB db, Article article) {
    		DBObject object = articleToObject2(article);
    		DBCollection articleCollection = db.getCollection("article");
    		articleCollection.insert(object);
    		return articleCollection;
    	}
    
    	//构造测试数据
    	private static Article buildArticle() {
    		Article article = new Article();
    		article.setAuthor("FansUnion");
    		article.setContent("neirong");
    		article.setDate(new Date());
    		article.setId(1L);
    		article.setTitle("title");
    		return article;
    	}
    
    	// 从集合中,根据ID查找
    	public static Article findById(DBCollection collection, Long id) {
    		BasicDBObject searchArticleById = new BasicDBObject();
    		searchArticleById.append(ID, id);
    		Article articleBefore = null;
    		DBCursor cursor = collection.find(searchArticleById);
    		while (cursor.hasNext()) {
    			DBObject articleObject = cursor.next();
    			articleBefore = objectToArticle(articleObject);
    
    			String internalId = articleObject.get("_id").toString();
    			articleBefore.setInternalId(internalId);
    		}
    		cursor.close();
    		return articleBefore;
    	}
    
    	// 修改
    	public static void update(DBCollection collection, Article article) {
    		if (article.getId() == null) {
    			return;
    		}
    
    		BasicDBObject updateCondition = new BasicDBObject();
    		updateCondition.append(ID, article.getId());
    
    		DBObject newObject = BeanUtil.bean2DBObject(article);
    
    		DBObject updateSetValue = new BasicDBObject("$set", newObject);
    		collection.update(updateCondition, updateSetValue);
    	}
    
    	//根据ID集合查找
    	public static List<Article> findByIdList(DBCollection collection,
    			List<Long> idList) {
    		BasicDBList values = new BasicDBList();
    		values.addAll(idList);
    
    		DBObject inQuery = new BasicDBObject("$in", values);
    
    		DBObject con = new BasicDBObject();
    		con.put(ID, inQuery);
    		DBCursor cursorIdArray = collection.find(con);
    
    		List<Article> articleList = new ArrayList<Article>();
    		while (cursorIdArray.hasNext()) {
    			DBObject articleObject = cursorIdArray.next();
    			Article article = new Article();
    			BeanUtil.dbObject2Bean(articleObject, article);
    			String internalId = articleObject.get("_id").toString();
    			article.setInternalId(internalId);
    
    			articleList.add(article);
    		}
    		return articleList;
    	}
    
    	//对象转换
    	private static Article objectToArticle(DBObject object) {
    		if (object == null) {
    			return null;
    		}
    		Article article = new Article();
    		// 用工具方法转换,手动转换,需要判断类型,比较麻烦
    		article = BeanUtil.dbObject2Bean(object, article);
    		return article;
    	}
    
    	// 手动把Bean转换为Mongodb的对象
    	private static BasicDBObject articleToObject(Article article) {
    		BasicDBObject object = new BasicDBObject();
    		object.append(TITLE, article.getTitle());
    		object.append(CONTENT, article.getContent());
    		object.append(AUTHOR, article.getAuthor());
    		object.append(DATE, article.getDate());
    		object.append(ID, article.getId());
    		return object;
    	}
    
    	// 实用工具转换,简单
    	private static DBObject articleToObject2(Article article) {
    		return BeanUtil.bean2DBObject(article);
    	}
    }
    

    和上一篇总结2的区别


    1.文章先用Java对象表示。

    public class Article {
    private Long id;
    private String title;
    private String content;
    private String author;
    private Date date;

    }

    2.Mongodb的参数用个配置类。

    public class MongodbConfig {


    private String host;
    private String port;
    private String db;

    }


    3.Mongodb获得连接,用个类表示。

    public class MongoUtil {
    	public static final int DEFAULT_PORT = 27017;
    	public static final String DEFAULT_HOST = "172.17.100.150";
    
    	private static Mongo instance;
    
    	@Resource(name="mongodbConfig")
    	private static MongodbConfig mongodbConfig;	
    	
    	public static Mongo mongo() {
    		try {
    			if (instance == null) {
    				instance = new Mongo(DEFAULT_HOST, DEFAULT_PORT);
    			}
    		} catch (UnknownHostException e) {
    			e.printStackTrace();
    		}
    		return instance;
    	}
    
    	public static void close() {
    		if (instance != null) {
    			instance.close();
    		}
    	}
    
    }

    4.Bean工具类,把Java对象和Mongodb对象进行转换。

    import java.lang.reflect.Field;
    import java.lang.reflect.InvocationTargetException;
    import java.util.Date;
    
    import org.apache.commons.beanutils.BeanUtils;
    import org.apache.commons.lang.ArrayUtils;
    
    import com.mongodb.BasicDBObject;
    import com.mongodb.DBObject;
    
    public class BeanUtil {
    
    	/**
    	 * 把实体bean对象转换成DBObject
    	 */
    	public static <T> DBObject bean2DBObject(T bean)
    	 {
    		if (bean == null) {
    			return null;
    		}
    		DBObject dbObject = new BasicDBObject();
    		// 获取对象对应类中的所有属性域
    		Field[] fields = bean.getClass().getDeclaredFields();
    		//父类的属性
    		Field[] parentFields=bean.getClass().getSuperclass().getDeclaredFields();
    		//合并
    		Field[] allFeilds=(Field[]) ArrayUtils.addAll(fields, parentFields);
    		for (Field field : allFeilds) {
    			// 获取属性名
    			String varName = field.getName();
    			// 修改访问控制权限
    			boolean accessFlag = field.isAccessible();
    			if (!accessFlag) {
    				field.setAccessible(true);
    			}
    			Object param;
    			try {
    				param = field.get(bean);
    				if (param == null) {
    					continue;
    				} else if (param instanceof Integer) {// 判断变量的类型
    					int value = ((Integer) param).intValue();
    					dbObject.put(varName, value);
    				} else if (param instanceof String) {
    					String value = (String) param;
    					dbObject.put(varName, value);
    				} else if (param instanceof Double) {
    					double value = ((Double) param).doubleValue();
    					dbObject.put(varName, value);
    				} else if (param instanceof Float) {
    					float value = ((Float) param).floatValue();
    					dbObject.put(varName, value);
    				} else if (param instanceof Long) {
    					long value = ((Long) param).longValue();
    					dbObject.put(varName, value);
    				} else if (param instanceof Boolean) {
    					boolean value = ((Boolean) param).booleanValue();
    					dbObject.put(varName, value);
    				} else if (param instanceof Date) {
    					Date value = (Date) param;
    					dbObject.put(varName, value);
    				}
    				// 恢复访问控制权限
    				field.setAccessible(accessFlag);
    			} catch (IllegalArgumentException | IllegalAccessException e) {
    				e.printStackTrace();
    			}
    			
    		}
    		return dbObject;
    	}
    
    	/**
    	 * 把DBObject转换成bean对象
    	 */
    	public static <T> T dbObject2Bean(DBObject dbObject, T bean) {
    		if (bean == null) {
    			return null;
    		}
    		Field[] fields = bean.getClass().getDeclaredFields();
    		Field[] parentFields=bean.getClass().getSuperclass().getDeclaredFields();
    		Field[] allFeilds=(Field[]) ArrayUtils.addAll(fields, parentFields);
    		for (Field field : allFeilds) {
    			String varName = field.getName();
    			Object object = dbObject.get(varName);
    			if (object != null) {
    				try {
    					BeanUtils.setProperty(bean, varName, object);
    				} catch (IllegalAccessException | InvocationTargetException e) {
    					e.printStackTrace();
    				}
    			}
    		}
    		return bean;
    	}
    }

    5.方法封装的,看起来更清晰。

    add、findById、update、findByIdList。

    上次的demo**,主要是演示。


    6.特别说明,BeanUtil中把Mongodb对象和Java对象互相转换的时候,要考虑到简单的继承"extends"情况。

  • 相关阅读:
    Pset_DistributionChamberElementTypeFormedDuct
    Pset_DistributionChamberElementTypeInspectionChamber
    Pset_DistributionChamberElementTypeInspectionPit
    错误日志
    Pset_DistributionChamberElementTypeManhole
    Pset_DistributionChamberElementTypeMeterChamber
    osg绘制立方体
    Pset_AlarmPHistory
    Pset_ActuatorTypeRotationalActuation
    Pset_ActuatorTypePneumaticActuator
  • 原文地址:https://www.cnblogs.com/qitian1/p/6462697.html
Copyright © 2011-2022 走看看