Java implementation of MongoDB Dbutils

Source: Internet
Author: User

MongoDB is used, but the operation return data calls the Find method to return the need to deal with, it is very uncomfortable, borrowed from the next commons-dbutils on the Java database operation, and also to MongoDB's return data implementation encapsulation. It uses Java introspection and reflection.

followed by the source code and simple comments

Person.java
Package Com.zk.bean;
/**
* User Entity
* @author ZK
* @time 2015-4-24 1:49:45
* @version 1.0
* @todo
*/
public class Person {
Private String ID;
private String name;

public String getId() {    return id;}public void setId(String id) {    this.id = id;}public String getName() {    return name;}public void setName(String name) {    this.name = name;}@Overridepublic String toString() {    return "Person [id=" + id + ", name=" + name + "]";}}

Resultsethandler.java

package com.zk.db.ResultHandler;import java.sql.ResultSet;import java.sql.SQLException;import java.util.Set;import com.mongodb.DBCursor;import com.mongodb.DBObject;/** * 通过接口 实现数据回调 * @author  zk * @time    2015-4-24 下午1:27:25 * @version 1.0 * @todo */public interface ResultSetHandler<T> {    /**     * 用户自己封装数据处理     * @param cursor     * @return     * @throws Exception     */    public T handler(DBCursor cursor) throws Exception;}

Basehandler.java

Package Com.zk.db.resulthandler;import Java.beans.beaninfo;import Java.beans.introspector;import Java.beans.propertydescriptor;import Java.lang.reflect.method;import Java.util.set;import com.mongodb.DBObject;/* * * Return Data processing base class to implement introspective encapsulation * @author ZK * @time 2015-4-24 PM 4:07:52 * @version 1.0 * @todo */public class basehandler<t& Gt    {Private Class clazz;        Public Basehandler (Class clazz) {this.clazz=clazz; TODO auto-generated Constructor stub} public void populate (T T, set<string> Set, DBObject object) throws E        Xception {//complete encapsulation of the data BeanInfo info = introspector.getbeaninfo (clazz);        PropertyDescriptor [] pds = Info.getpropertydescriptors ();            for (PropertyDescriptor Pd:pds) {//Gets the name of the property first proname String proname = Pd.getname ();                if (Set.contains (proname)) {//gets to the Write method of the property methods M = Pd.getwritemethod (); M.invoke of Execution (T, Object.get (pRoname));                } if (Set.contains ("_" +proname)) {//Gets the Write method to the property methods M = Pd.getwritemethod ();            M.invoke of Execution (T,object.get ("_" +proname)); }        }    }}

Beanhandler.java
Package com.zk.db.ResultHandler;
Import Java.beans.BeanInfo;
Import Java.beans.Introspector;
Import Java.beans.PropertyDescriptor;
Import Java.lang.reflect.Method;
Import Java.lang.reflect.ParameterizedType;
Import Java.lang.reflect.Type;
Import java.util.ArrayList;
Import java.util.List;
Import Java.util.Set;
Import Com.mongodb.DBCursor;
Import Com.mongodb.DBObject;

/** * Returns the processing of a single record entity * * @author ZK * @time 2015-4-24 PM 3:51:32 * @version 1.0 * @todo */public class beanhandler<t> E    Xtends Basehandler<t> implements resultsethandler<t> {private Class clazz;        Public Beanhandler (Class clazz) {super (clazz);    This.clazz = Clazz; }/** * Callback processing Core method */Public T handler (dbcursor cursor) throws Exception {try {if (cursor.ha                Snext ()) {//reflection mechanism T t = (t) this.clazz.newInstance ();                DBObject object = Cursor.next ();                set<string> set = Object.keyset ();                Populate (T, set, object);            return t;        }} catch (Exception e) {e.printstacktrace ();    } return null; }}**beanlisthandler.java**package Com.zk.db.resulthandler;import Java.beans.beaninfo;import Java.beans.introspector;import Java.beans.propertydescriptor;import Java.lang.reflect.method;import Java.lang.reflecT.parameterizedtype;import Java.lang.reflect.type;import Java.util.arraylist;import Java.util.List;import Java.util.set;import Com.mongodb.dbcursor;import com.mongodb.dbobject;/** * Returns the processing of the list generic collection * * @author ZK * @time 2015-4- 24 pm 3:50:19 * @version 1.0 * @todo */public class Beanlisthandler<t> extends basehandler<t> implements Result    sethandler<list<t>> {private Class clazz;        Public Beanlisthandler (Class clazz) {super (clazz);    This.clazz = Clazz;            }/** * Callback Data Processing Core method */Public list<t> handler (dbcursor cursor) throws Exception {try {            list<t> list = new arraylist<t> ();                while (Cursor.hasnext ()) {//reflection t T = (t) this.clazz.newInstance ();                DBObject object = Cursor.next ();                set<string> set = Object.keyset ();                Populate (T, set, object);            List.add (t);        } return list; } catch (Exception e) {//TODO auto-generated catch block E.printstacktrace ();    } return null; }}

The

Mongodb.java can call this method directly later, and it needs to be optimized for processing

Package Com.zk.db;import Java.net.unknownhostexception;import Java.sql.sqlexception;import java.util.List;import Java.util.set;import Org.bson.types.objectid;import Org.junit.test;import Com.mongodb.basicdbobject;import Com.mongodb.db;import Com.mongodb.dbcollection;import Com.mongodb.dbcursor;import Com.mongodb.DBObject;import Com.mongodb.mongo;import Com.mongodb.mongoexception;import Com.zk.bean.person;import Com.zk.db.resulthandler.beanlisthandler;import Com.zk.db.resulthandler.resultsethandler;public class MongoDb {//1. Establish a Mongo database connection object static Mongo connection = null;//2. To create a connection to a related database static db db = Null;public MongoDb (String dbName) throws Un    Knownhostexception, mongoexception {connection = new Mongo ("127.0.0.1:27017"); db = Connection.getdb (dbName);} public static void Main (string[] args) throws Unknownhostexception, mongoexception {MongoDB MongoDB = new Mongo    Db ("one");    DBObject query = new Basicdbobject ();    Look at this place is not very like dbutils called Method yo ..... List<person>    plist = mongodb.find (query, New beanlisthandler<person> (Person.class), "person");    for (person person:plist) {System.out.println (person); }}/** * Paged query returns PACKAGE Collection * @param query * @param rsh * @param collname * @return */public <T> T fin        D (dbobject query, resultsethandler<t> rsh, String collname) {try {MongoDB MongoDB = new MongoDB ("one");        MONGODB.F dbcursor cursor = mongodb.find (null, NULL, 0, 6, collname);        Key, the user decides how to encapsulate the RS object List Map account ...        T t = rsh.handler (cursor);    return t;        } catch (Exception e) {//TODO auto-generated catch block E.printstacktrace ();    throw new RuntimeException (e); }//Call encapsulates the result of the method that returns the encapsulated result. }/** * Finder (paging) * * @param ref * @param keys * @param start * @param limit * @return */public dbcursor find (dbobject ref,    dbobject keys, int start, int limit, String collname) {dbcursor cur = find (ref, keys, collname); REturn cur.limit (limit). Skip (start); /** * Finder (no paging) * * @param ref * @param keys * @param start * @param limit * @param collname * @return */public dbcursor F    IND (dbobject ref, DBObject keys, String collname) {//1. Get set Dbcollection coll = db.getcollection (collname);    Dbcursor cur = coll.find (ref, keys); return cur;}}

Note:
Basehandler class return data processing base class implementation introspection encapsulation
Resultsethandler interface implements data callback via interface
Beanhandler class returns the processing of a single record entity
Beanlisthandler returns the processing of a list generic collection
The MongoDB class core processes public T find (dbobject query, Resultsethandler rsh, String collname) to connect these classes of interfaces, and when the method is called, You need to pass in a class that implements the Resultsethandler interface, which can be basehandler[return a single entity],beanlisthandler[return a list collection], and within the method you can invoke the handler method of the concrete implementation class. Implementation of specific parsing, return. Basehandler can help beanlisthandler,beanhandler these 2 implementation classes take advantage of reflection to encapsulate the effect of data.
This implementation draws on the implementation of the Open Source Tool class Dbutils. Interface-oriented programming, interface injection, reflective introspection can also be used in this area.
In addition, there are some open source operation MongoDB Dbtuils and ORM Framework, can go to look for reference.

Java implementation of MongoDB Dbutils

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.