package com.mongo; import java.net.UnknownHostException; import com.google.gson.Gson; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; import com.mongodb.MongoClient; import com.mongodb.util.JSON; public class Main { /** * @param args * @throws UnknownHostException */ public static void main(String[] args) throws UnknownHostException { // TODO Auto-generated method stub MongoClient mongoClient = new MongoClient(); DB psdoc = mongoClient.getDB("psdoc"); DBCollection user=psdoc.getCollection("user"); User u1=new User(); u1.setAge(20); u1.setName("ssss"); Gson gson=new Gson(); //转换成json字符串,再转换成DBObject对象 DBObject dbObject = (DBObject) JSON.parse(gson.toJson(u1)); //插入数据库 user.insert(dbObject); DBCursor cursor=user.find(); while(cursor.hasNext()) { DBObject obj=cursor.next(); //反转 User u=gson.fromJson(obj.toString(), User.class); System.out.println(u.name); } } } 为了方便,可以直接把Gson整合进驱动里,直接修改驱动的源代码 com.mongodb.DBCollection.java: 新增方法:
代码如下 | 复制代码 | /** * 把普通的对象写入数据库 * * @param obj * @return */ public WriteResult insert(Object obj) { Gson gson = new Gson(); DBObject dbObject = (DBObject) JSON.parse(gson.toJson(obj)); gson=null; return insert(dbObject); } com.mongodb.DBCursor.java: 新增方法
代码如下 | 复制代码 | /** * 从数据库读出对象 * @param obj * @param clazz * @return */ public T nextObj(Class clazz) { _checkType( CursorType.ITERATOR ); Gson gson=new Gson(); T u=gson.fromJson(_next().toString(), clazz); gson=null; return u; } 修改后的调用方法:
代码如下 | 复制代码 | Main.java: package com.mongo; import java.net.UnknownHostException; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.MongoClient; public class Main { /** * @param args * @throws UnknownHostException */ public static void main(String[] args) throws UnknownHostException { // TODO Auto-generated method stub MongoClient mongoClient = new MongoClient(); DB psdoc = mongoClient.getDB("psdoc"); DBCollection user=psdoc.getCollection("user"); User u1=new User(); u1.setAge(20); u1.setName("ssss"); //直接插入对象 user.insert(u1); DBCursor cursor=user.find(); while(cursor.hasNext()) { //传入类参数,反回该类对象 User u=cursor.nextObj(User.class); System.out.println(u.name); } } } |
|
|
|