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」を継承する場合を考慮する.
本文はブロガーのオリジナル文章で、ブロガーの許可を得ずに転載してはならない.