Java Implementation of mongodb dbutils
Mongodb is used up, but it is uncomfortable to call the find method to return the data returned by the operation. I used commons-dbutils for java database operations, you can encapsulate the data returned by mongodb. It uses java introspection and reflection.
Next, paste the source code and simple comments.
Person. java
Package com. zk. bean;
/**
* User entity
* @ Author zk
* @ Time 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; } @Override public 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;/*** implement data callback through the interface * @ author zk * @ time 1:27:25 * @ version 1.0 * @ todo */public interface ResultSetHandler
{/*** Encapsulate data processing by yourself * @ 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 the data processing base class to implement the introspection encapsulation * @ author zk * @ time 4:07:52 * @ version 1.0 * @ todo */public class BaseHandler
{Private Class clazz; public BaseHandler (Class clazz) {this. clazz = clazz; // TODO Auto-generated constructor stub} public void populate (T t, Set
Set, DBObject object) throws Exception {// encapsulate the data BeanInfo info = Introspector. getBeanInfo (clazz); PropertyDescriptor [] PPS = info. getPropertyDescriptors (); for (PropertyDescriptor pd: PPS) {// obtain the property name proName String proName = pd first. getName (); if (set. contains (proName) {// write Method to obtain this attribute m = pd. getWriteMethod (); // execute m. invoke (t, object. get (proName);} if (set. contains ("_" + proName) {// Method m = pd for obtaining the property. getWriteMethod (); // execute m. invoke (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;
/*** Return the processing of a single record entity *** @ author zk * @ time 3:51:32 * @ version 1.0 * @ todo */public class BeanHandler
Extends BaseHandler
Implements ResultSetHandler
{Private Class clazz; public BeanHandler (Class clazz) {super (clazz); this. clazz = clazz;}/*** core callback Processing Method */public T handler (DBCursor cursor) throws Exception {try {if (cursor. hasNext () {// reflection mechanism T t = (T) this. clazz. newInstance (); DBObject object = cursor. next (); Set
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;
/*** Return the processing of list generic sets ** @ author zk * @ time 3:50:19 * @ version 1.0 * @ todo */public class BeanListHandler
Extends BaseHandler
Implements ResultSetHandler
> {Private Class clazz; public BeanListHandler (Class clazz) {super (clazz); this. clazz = clazz;}/*** core callback Data Processing Method */public List
Handler (DBCursor cursor) throws Exception {try {List
List = new ArrayList
(); While (cursor. hasNext () {// reflection T t = (T) this. clazz. newInstance (); DBObject object = cursor. next (); Set
Set = object. keySet (); populate (t, set, object); list. add (t);} return list;} catch (Exception e) {// TODO Auto-generated catch block e. printStackTrace ();} return null ;}}
MongoDb. java can call this method directly and needs optimization.
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. except exception; import com. zk. bean. Person; import com. zk. db. resultHandler. beanListHandler; import com. zk. db. resultHandler. resultSetHandler; public class MongoDb {// 1. create a Mongo database connection object static Mongo connection = null; // 2. create a connection to the relevant database static DB db = null; public MongoDb (String dbName) throws UnknownHostException, unknown exception {connection = new Mongo ("127.0.0.1: 27017"); db = connection. getDB (dbName);} public static void main (String [] args) Throws UnknownHostException, writable exception {MongoDb mongoDb = new MongoDb ("one"); DBObject query = new BasicDBObject (); // check whether the method called by dbutils is similar ..... List
Plist = mongoDb. find (query, new BeanListHandler
(Person. class), "person"); for (Person person: plist) {System. out. println (person) ;}}/*** returns the encapsulated set in paging query * @ param rsh * @ param collName * @ return */public
T find (DBObject query, ResultSetHandler
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 the method for encapsulating the result and return the encapsulated result .} /*** Queryer (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);}/*** queryer (not paging) ** @ param ref * @ param keys * @ param start * @ param limit * @ param collName * @ return */public DBCursor find (DBObject ref, DBObject keys, String collName) {// 1. obtain the collection DBCollection coll = db. getCollection (collName); DBCursor cur = coll. find (ref, keys); return cur ;}}
Note:
BaseHandler class returns the data processing base class for introspection Encapsulation
The ResultSetHandler interface implements data callback through the interface
BeanHandler class returns processing of a single record entity
BeanListHandler returns the processing of list generic Sets
MongoDb class core processes public T find (DBObject query, ResultSetHandler rsh, String collName) to connect these class interfaces. When this method is called, you need to input a class that implements the ResultSetHandler interface. This class can be BaseHandler [returns a single object], BeanListHandler [returns a list set], and the handler method of the specific implementation class can be called inside the method, implements specific parsing and returns. BaseHandler can help BeanListHandler and BeanHandler to encapsulate data using reflection.
This implementation draws on the implementation of the open-source tool class dbutils. Interface-oriented programming, interface injection, and reflection can also be reflected here.
In addition, there are some open-source mongodb dbtuils and orm frameworks on the Internet, which can be used for reference.