通过阅读MongoDB 3.2.1的官方文档中关于java 编程发现最新的文档并没有实现对对象到Document的映射,所以自己有了利用反射实现简单的关系映射.
1.定义抽象类:AbstractMongoSession
importjava.util.List;importorg.bson.Document;importorg.bson.conversions.Bson;importcom.mongodb.client.MongoCollection;importcom.mongodb.client.MongoDatabase;/** 创建一个会话实现对mongoDB的原子操作
*
* @author:maybo
*
* @date:2016-2-1*/
public abstract classAbstractMongoSession {privateMongoDatabase db;private Class>clazz;private MongoCollectioncollection;public MongoCollectiongetCollection() {return this.collection;
}public Class>getClazz() {returnclazz;
}public voidsetDb(MongoDatabase db) {this.db =db;
}publicMongoDatabase getDb() {returndb;
}protected MongoCollection Collection(Class>clazz) {this.clazz =clazz;
Table table= (Table) clazz.getAnnotation(Table.class);
String col= null;if (null != table && null !=table.name()) {
col=table.name();
}else{
col=clazz.getName();
}this.collection =db.getCollection(col);return this.collection;
}/** 保存
*
* @param:实体
*
* @return:void*/
public abstract voidsave(Object obj);public abstract void saveMany(Listobj);//删除数据
public abstract long delete(Object obj) throwsException;public abstract long delete(Bson bson) throwsException;//删除数据
public abstract long deleteMany(Listobjs);public abstract longdeleteMany(Bson bson);//修改数据
public abstract longupate(Bson bson, Object obj);public abstract longupdate(Object obj);public abstract longupateMany(Bson bson, Object obj);public abstract long upateMany(Bson bson, Listobjs);public abstract long upateMany(Listobjs);//查询数据
public abstractObject find(Object obj);//获取所有的数据
public abstract Listfinds();//条件查询数据
public abstract Listquery(Bson bson);public abstractObject queryOne(Bson bson);public abstract Listquery(Bson bson, Bson sort);public abstractObject queryOne(Bson bson, Bson sort);public abstract List query(Bson bson, Bson sort, intlimit);public abstract List query(Bson bson, Bson sort, int limit, intskip);public abstract Listquery(Bson bson, Bson sort, Bson filter);public abstractObject queryOne(Bson bson, Bson sort, Bson Filter);public abstract longcount();public abstract longcount(Bson bson);
}
2. 实现类MongoSession
importjava.lang.reflect.InvocationTargetException;importjava.util.ArrayList;importjava.util.List;importorg.bson.Document;importorg.bson.conversions.Bson;importcom.mongodb.client.FindIterable;importcom.mongodb.client.MongoCursor;importcom.mongodb.client.MongoDatabase;importcom.mongodb.client.model.Filters;importcom.mongodb.client.result.DeleteResult;importcom.mongodb.client.result.UpdateResult;public class MongoSession extendsAbstractMongoSession {public MongoSession(Class>clazz, MongoDatabase db) {this.setDb(db);this.Collection(clazz);
}/** (non-Javadoc)
*
* @see AbstractMongoSession#save(java.lang.Object)*/@Overridepublic voidsave(Object obj) {try{this.getCollection().insertOne(BsonUtil.toBson(obj));
}catch(IllegalArgumentException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(SecurityException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(IllegalAccessException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(InvocationTargetException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(NoSuchFieldException e) {//TODO Auto-generated catch block
e.printStackTrace();
}
}
@Overridepublic long delete(Object obj) throwsException {try{
DeleteResult result= this.getCollection().deleteOne(
BsonUtil.toBson(obj));long count =result.getDeletedCount();returncount;
}catch(IllegalArgumentException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(SecurityException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(IllegalAccessException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(InvocationTargetException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(NoSuchFieldException e) {//TODO Auto-generated catch block
e.printStackTrace();
}return 0;
}
@Overridepublic void saveMany(Listobj) {try{this.getCollection().insertMany(BsonUtil.toBsons(obj));
}catch(IllegalArgumentException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(SecurityException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(IllegalAccessException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(InvocationTargetException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(NoSuchFieldException e) {//TODO Auto-generated catch block
e.printStackTrace();
}
}
@Overridepublic long delete(Bson bson) throwsException {
DeleteResult deleteResult= this.getCollection().deleteOne(bson);returndeleteResult.getDeletedCount();
}
@Overridepublic long deleteMany(Listobjs) {
Listdocuments;int count = 0;try{
documents=BsonUtil.toBsons(objs);for (int i = 0; null != documents && i < documents.size(); i++) {
DeleteResult deleteResult= this.getCollection().deleteOne(
documents.get(i));
count+=deleteResult.getDeletedCount();
}returncount;
}catch(IllegalArgumentException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(SecurityException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(IllegalAccessException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(InvocationTargetException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(NoSuchFieldException e) {//TODO Auto-generated catch block
e.printStackTrace();
}returncount;
}
@Overridepublic longdeleteMany(Bson bson) {
DeleteResult deleteResult= this.getCollection().deleteMany(bson);returndeleteResult.getDeletedCount();
}
@Overridepublic longupate(Bson bson, Object obj) {try{
UpdateResult result= this.getCollection().updateOne(bson,new Document("$set", BsonUtil.toBson(obj)));returnresult.getMatchedCount();
}catch(IllegalArgumentException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(SecurityException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(IllegalAccessException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(InvocationTargetException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(NoSuchFieldException e) {//TODO Auto-generated catch block
e.printStackTrace();
}return 0;
}
@Overridepublic longupdate(Object obj) {
Document document;try{
document=BsonUtil.toBson(obj);
UpdateResult updateResult= this.getCollection().updateOne(
Filters.eq("_id", document.get("_id")),new Document("$set", document));returnupdateResult.getMatchedCount();
}catch(IllegalArgumentException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(SecurityException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(IllegalAccessException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(InvocationTargetException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(NoSuchFieldException e) {//TODO Auto-generated catch block
e.printStackTrace();
}return 0;
}
@Overridepublic longupateMany(Bson bson, Object obj) {try{
UpdateResult updateResult= this.getCollection().updateMany(bson,new Document("$set", BsonUtil.toBson(obj)));returnupdateResult.getMatchedCount();
}catch(IllegalArgumentException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(SecurityException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(IllegalAccessException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(InvocationTargetException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(NoSuchFieldException e) {//TODO Auto-generated catch block
e.printStackTrace();
}return 0;
}
@Overridepublic long upateMany(Bson bson, Listobj) {for (int i = 0; null != obj && i < obj.size(); i++) {try{
UpdateResult result= this.getCollection().updateMany(bson,new Document("$set", BsonUtil.toBson(obj)));returnresult.getMatchedCount();
}catch(IllegalArgumentException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(SecurityException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(IllegalAccessException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(InvocationTargetException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(NoSuchFieldException e) {//TODO Auto-generated catch block
e.printStackTrace();
}
}return 0;
}
@Overridepublic long upateMany(Listobjs) {long count = 0;for (int i = 0; null != objs && i < objs.size(); i++) {try{
UpdateResult result= this.getCollection().updateMany(
Filters.eq("_id",
BsonUtil.toBson(objs.get(i)).get("_id")),new Document("$set", BsonUtil.toBson(objs.get(i))));
count+=result.getMatchedCount();
}catch(IllegalArgumentException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(SecurityException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(IllegalAccessException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(InvocationTargetException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(NoSuchFieldException e) {//TODO Auto-generated catch block
e.printStackTrace();
}
}returncount;
}
@OverridepublicObject find(Object obj) {try{
Document document= this.getCollection()
.find(Filters.eq("_id", BsonUtil.toBson(obj).get("_id")))
.first();return BsonUtil.toBean(document, this.getClazz());
}catch(IllegalArgumentException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(SecurityException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(IllegalAccessException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(InvocationTargetException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(NoSuchFieldException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(InstantiationException e) {//TODO Auto-generated catch block
e.printStackTrace();
}return null;
}
@Overridepublic Listfinds() {
FindIterable doIterable = this.getCollection().find();
MongoCursor cursor =doIterable.iterator();
List objects = new ArrayList();while(cursor.hasNext()) {
Document document=cursor.next();try{
objects.add(BsonUtil.toBean(document,this.getClazz()));
}catch(IllegalArgumentException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(InstantiationException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(IllegalAccessException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(InvocationTargetException e) {//TODO Auto-generated catch block
e.printStackTrace();
}
}returnobjects;
}
@Overridepublic Listquery(Bson bson) {
FindIterable doIterable = this.getCollection().find(bson);
MongoCursor cursor =doIterable.iterator();
List objects = new ArrayList();while(cursor.hasNext()) {
Document document=cursor.next();try{
objects.add(BsonUtil.toBean(document,this.getClazz()));
}catch(IllegalArgumentException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(InstantiationException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(IllegalAccessException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(InvocationTargetException e) {//TODO Auto-generated catch block
e.printStackTrace();
}
}returnobjects;
}
@OverridepublicObject queryOne(Bson bson) {
Document document= this.getCollection().find(bson).first();try{return BsonUtil.toBean(document, this.getClazz());
}catch(IllegalArgumentException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(InstantiationException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(IllegalAccessException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(InvocationTargetException e) {//TODO Auto-generated catch block
e.printStackTrace();
}return null;
}
@Overridepublic Listquery(Bson bson, Bson sort) {
FindIterable doIterable = this.getCollection().find(bson)
.sort(sort);
MongoCursor cursor =doIterable.iterator();
List objects = new ArrayList();while(cursor.hasNext()) {
Document document=cursor.next();try{
objects.add(BsonUtil.toBean(document,this.getClazz()));
}catch(IllegalArgumentException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(InstantiationException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(IllegalAccessException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(InvocationTargetException e) {//TODO Auto-generated catch block
e.printStackTrace();
}
}returnobjects;
}
@OverridepublicObject queryOne(Bson bson, Bson sort) {
Document document= this.getCollection().find(bson).sort(sort).first();try{return BsonUtil.toBean(document, this.getClazz());
}catch(IllegalArgumentException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(InstantiationException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(IllegalAccessException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(InvocationTargetException e) {//TODO Auto-generated catch block
e.printStackTrace();
}return null;
}
@Overridepublic List query(Bson bson, Bson sort, intlimit) {
FindIterable doIterable = this.getCollection().find(bson)
.sort(sort);if (limit > 0) {
doIterable=doIterable.limit(limit);
}
MongoCursor cursor =doIterable.iterator();
List objects = new ArrayList();while(cursor.hasNext()) {
Document document=cursor.next();try{
objects.add(BsonUtil.toBean(document,this.getClazz()));
}catch(IllegalArgumentException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(InstantiationException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(IllegalAccessException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(InvocationTargetException e) {//TODO Auto-generated catch block
e.printStackTrace();
}
}returnobjects;
}
@Overridepublic List query(Bson bson, Bson sort, int limit, intskip) {
FindIterable doIterable = this.getCollection().find(bson)
.sort(sort);if (limit > 0) {
doIterable=doIterable.limit(limit);
}if (skip > 0) {
doIterable=doIterable.skip(skip);
}
MongoCursor cursor =doIterable.iterator();
List objects = new ArrayList();while(cursor.hasNext()) {
Document document=cursor.next();try{
objects.add(BsonUtil.toBean(document,this.getClazz()));
}catch(IllegalArgumentException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(InstantiationException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(IllegalAccessException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(InvocationTargetException e) {//TODO Auto-generated catch block
e.printStackTrace();
}
}returnobjects;
}
@Overridepublic Listquery(Bson bson, Bson sort, Bson filter) {
FindIterable doIterable = this.getCollection().find(bson)
.sort(sort).filter(filter);
MongoCursor cursor =doIterable.iterator();
List objects = new ArrayList();while(cursor.hasNext()) {
Document document=cursor.next();try{
objects.add(BsonUtil.toBean(document,this.getClazz()));
}catch(IllegalArgumentException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(InstantiationException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(IllegalAccessException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(InvocationTargetException e) {//TODO Auto-generated catch block
e.printStackTrace();
}
}returnobjects;
}
@OverridepublicObject queryOne(Bson bson, Bson sort, Bson Filter) {
Document document= this.getCollection().find(bson).sort(sort)
.filter(Filter).first();try{return BsonUtil.toBean(document, this.getClazz());
}catch(IllegalArgumentException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(InstantiationException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(IllegalAccessException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(InvocationTargetException e) {//TODO Auto-generated catch block
e.printStackTrace();
}return null;
}
@Overridepublic longcount() {return this.getCollection().count();
}
@Overridepublic longcount(Bson bson) {//TODO Auto-generated method stub
return this.getCollection().count(bson);
}
}
3. 帮助类:实现Document到Object 以及Object到Document的转换.使用反射技术和注解.
importjava.lang.reflect.Field;importjava.lang.reflect.InvocationTargetException;importjava.lang.reflect.Method;importjava.lang.reflect.ParameterizedType;importjava.util.ArrayList;importjava.util.List;importorg.bson.Document;importcom.mongodb.client.MongoCollection;importcom.mongodb.client.MongoCursor;/** 将mongo的文档转化为对象将对象转化为mongo文档
* @author:maybo
* @data:2016-2-1*/
public classBsonUtil {public static List toBeans(List documents, Classclazz)throwsIllegalArgumentException, InstantiationException,
IllegalAccessException, InvocationTargetException {
List list = new ArrayList();for (int i = 0; null != documents && i < documents.size(); i++) {
list.add(toBean(documents.get(i), clazz));
}returnlist;
}/** 将Bson 转化为对象
*
* @param:Bson文档
*
* @param:类pojo
*
* @param:返回对象*/
public static T toBean(Document document, Classclazz)throwsInstantiationException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
T obj= clazz.newInstance();//声明一个对象
Field[] fields = clazz.getDeclaredFields();//获取所有属性
Method[] methods = clazz.getMethods();//获取所有的方法
/** 查找所有的属性,并通过属性名和数据库字段名通过相等映射*/
for (int i = 0; i < fields.length; i++) {
String fieldName=fields[i].getName();
Column column= fields[i].getAnnotation(Column.class);
Object bson= null;if (null != column && null !=column.name()) {
bson=document.get(column.name());
}else if ("id".equals(fieldName)) {
bson= document.get("_id");
}else{
bson=document.get(fieldName);
}if (null ==bson) {continue;
}else if (bson instanceof Document) {//如果字段是文档了递归调用
bson =toBean((Document) bson, fields[i].getType());
}else if (bson instanceof MongoCollection) {//如果字段是文档集了调用colTOList方法
bson=colToList(bson, fields[i]);
}for (int j = 0; j < methods.length; j++) {//为对象赋值
String metdName =methods[j].getName();if(equalFieldAndSet(fieldName, metdName)) {
methods[j].invoke(obj, bson);break;
}
}
}returnobj;
}public static List toBsons(Listobjs)throwsIllegalArgumentException, SecurityException,
IllegalAccessException, InvocationTargetException,
NoSuchFieldException {
List documents = new ArrayList();for (int i = 0; null != objs && i < objs.size(); i++) {
documents.add(toBson(objs.get(i)));
}returndocuments;
}/** 将对象转化为Bson文档
*
* @param:对象
*
* @param:类型
*
* @return:文档*/
public static Document toBson(Object obj) throwsIllegalArgumentException,
IllegalAccessException, InvocationTargetException,
SecurityException, NoSuchFieldException {if (null ==obj) {return null;
}
Class extends Object> clazz =obj.getClass();
Document document= newDocument();
Method[] methods=clazz.getDeclaredMethods();
Field[] fields=clazz.getDeclaredFields();for (int i = 0; null != fields && i < fields.length; i++) {
Column column= fields[i].getAnnotation(Column.class);//获取列注解内容
NotColumn notColumn = fields[i].getAnnotation(NotColumn.class);//获取否列
String key = null;//对应的文档键值
if (null != column && null != column.name()) {//存在列映射取值
key =column.name();
}else if (null != notColumn) {//不是列的情况
continue;
}else{
key= fields[i].getName();//默认情况通过属性名映射
if ("id".equals(key)) {//替换id为_id
key = "_id";
}
}
String fieldName=fields[i].getName();/** 获取对象属性值并映射到Document中*/
for (int j = 0; null != methods && j < methods.length; j++) {
String methdName=methods[j].getName();if (null != fieldName &&equalFieldAndGet(fieldName, methdName)) {
Object val= methods[j].invoke(obj);//得到值
if (null ==val) {continue;
}if(isJavaClass(methods[j].getReturnType())) {if(methods[j].getReturnType().getName()
.equals("java.util.List")) {//列表处理
@SuppressWarnings("unchecked")
List list = (List) val;
List documents = new ArrayList();for(Object obj1 : list) {
documents.add(toBson(obj1));
}
document.append(key, documents);
}else {//其它对象处理,基本类型
document.append(key, val);
}
}else {//自定义类型
document.append(key, toBson(val));
}
}
}
}returndocument;
}/** 是否是自定义类型】
*
* false:是自定义*/
private static boolean isJavaClass(Class>clz) {return clz != null && clz.getClassLoader() == null;
}/** 将文档集转化为列表
*
* @param:文档集
*
* @param:属性类型
*
* @return:返回列表*/
private static ListcolToList(Object bson, Field field)throwsInstantiationException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
ParameterizedType pt= (ParameterizedType) field.getGenericType();//获取列表的类型
List objs = new ArrayList();
@SuppressWarnings("unchecked")
MongoCollection cols = (MongoCollection) bson;
MongoCursor cursor =cols.find().iterator();while(cursor.hasNext()) {
Document child=cursor.next();
@SuppressWarnings("rawtypes")
Class clz= (Class) pt.getActualTypeArguments()[0];//获取元素类型
@SuppressWarnings("unchecked")
Object obj=toBean(child, clz);
System.out.println(child);
objs.add(obj);
}returnobjs;
}/** 比较setter方法和属性相等*/
private static booleanequalFieldAndSet(String field, String name) {if (name.toLowerCase().matches("set" +field.toLowerCase())) {return true;
}else{return false;
}
}/** 比较getter方法和属性相等*/
private static booleanequalFieldAndGet(String field, String name) {if (name.toLowerCase().matches("get" +field.toLowerCase())) {return true;
}else{return false;
}
}
}
4.用到的注解Column ,NotColumn,Table
Column:
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Column {
public String name();
public String text() default "这是一个属性映射";
}
N otColumn:
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface NotColumn {
public String text() default "不是属性字段";
}
Table:
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Table {
public String name();
public String text() default "表格映射";
}
5. MongoObject
import java.util.ArrayList;
import java.util.List;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.ReadPreference;
import com.mongodb.ServerAddress;
import com.mongodb.WriteConcern;
public class MongoObject {
private List hostPorts;
private int port=27017;
private String host="127.0.0.1";
private int connectionsPerHost=5;// 每个主机的连接数
private int threadsAllowedToBlockForConnectionMultiplier=30;// 线程队列数,它以上面connectionsPerHost值相乘的结果就是线程队列最大值。如果连接线程排满了队列就会抛出“Out
// // to get
// db”错误。
private long maxWaitTime=5000;// 最大等待连接的线程阻塞时间
private long connectTimeout=5000;// 连接超时的毫秒。0是默认和无限
private long socketTimeout=5000;// socket超时。0是默认和无限
private boolean autoConnectRetry=false;// 这个控制是否在一个连接时,系统会自动
public void setHostPorts(List hostPorts) {
this.hostPorts = hostPorts;
}
public MongoObject() {
// TODO Auto-generated constructor stub
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getConnectionsPerHost() {
return connectionsPerHost;
}
public void setConnectionsPerHost(int connectionsPerHost) {
this.connectionsPerHost = connectionsPerHost;
}
public int getThreadsAllowedToBlockForConnectionMultiplier() {
return threadsAllowedToBlockForConnectionMultiplier;
}
public void setThreadsAllowedToBlockForConnectionMultiplier(
int threadsAllowedToBlockForConnectionMultiplier) {
this.threadsAllowedToBlockForConnectionMultiplier = threadsAllowedToBlockForConnectionMultiplier;
}
public long getMaxWaitTime() {
return maxWaitTime;
}
public void setMaxWaitTime(long maxWaitTime) {
this.maxWaitTime = maxWaitTime;
}
public long getConnectTimeout() {
return connectTimeout;
}
public void setConnectTimeout(long connectTimeout) {
this.connectTimeout = connectTimeout;
}
public long getSocketTimeout() {
return socketTimeout;
}
public void setSocketTimeout(long socketTimeout) {
this.socketTimeout = socketTimeout;
}
public boolean isAutoConnectRetry() {
return autoConnectRetry;
}
public void setAutoConnectRetry(boolean autoConnectRetry) {
this.autoConnectRetry = autoConnectRetry;
}
public MongoClient run() {
if (null != hostPorts) {
if (null != host && port > 0) {
hostPorts.add(host + ":" + port);
}
} else {
hostPorts = new ArrayList();
if (null != host && port > 0) {
hostPorts.add(host + ":" + port);
} else {
return null;
}
}
List addresses = new ArrayList();
for (String hostPort : hostPorts) {
String[] spits = hostPort.split(":");
ServerAddress address = new ServerAddress(spits[0],
Integer.valueOf(spits[1]));
addresses.add(address);
}
MongoClient client = new MongoClient(addresses, getConfOptions());
return client;
}
@SuppressWarnings("deprecation")
private MongoClientOptions getConfOptions() {
return new MongoClientOptions.Builder()
.socketKeepAlive(true)
// 是否保持长链接
.connectTimeout((int) this.connectTimeout)
// 链接超时时间
.socketTimeout((int) this.socketTimeout)
// read数据超时时间
.readPreference(ReadPreference.primary())
// 最近优先策略
.connectionsPerHost(this.connectionsPerHost)
// 每个地址最大请求数
.maxWaitTime((int) this.maxWaitTime)
// 长链接的最大等待时间
.threadsAllowedToBlockForConnectionMultiplier(
this.threadsAllowedToBlockForConnectionMultiplier) // 一个socket最大的等待请求数
.writeConcern(WriteConcern.NORMAL).build();
}
}
6.MongoDB用于生产数据库对象
import com.mongodb.client.MongoDatabase;
public class MongoDB{
private String db;
private MongoObject client;
public void setClient(MongoObject client) {
this.client = client;
}
public void setDb(String db) {
this.db = db;
}
public MongoDB(MongoObject client,String db){
this.client=client;
this.db=db;
}
public MongoDatabase excute(){
return client.run().getDatabase(db);
}
}
7.DaoImpl
importjava.util.List;public class DaoImpl implementsDao{privateMongoTemplate template;privateMongoSession session;privateString className;public voidsetClassName(String className) {this.className =className;
}publicMongoSession getSession() {returnsession;
}publicDaoImpl(){}publicDaoImpl(MongoTemplate template,String className){this.template =template;this.className=className;try{this.session=template.session(Class.forName(className));
}catch(ClassNotFoundException e) {//TODO Auto-generated catch block
e.printStackTrace();
}
}public voidsetTemplate(MongoTemplate template) {this.template =template;try{this.session=template.session(Class.forName(className));
}catch(ClassNotFoundException e) {//TODO Auto-generated catch block
e.printStackTrace();
}
}
@Overridepublic voidsave(Object obj) {this.session.save(obj);
}
@Overridepublic voiddelete(Object obj) {try{this.session.delete(obj);
}catch(Exception e) {//TODO Auto-generated catch block
e.printStackTrace();
}
}
@Overridepublic voidupdate(Object obj) {this.session.update(obj);
}
@OverridepublicObject find(Object obj) {//TODO Auto-generated method stub
return this.session.find(obj);
}
@Overridepublic Listfinds() {//TODO Auto-generated method stub
return this.session.finds();
}
@Overridepublic longtotal() {//TODO Auto-generated method stub
return this.session.count();
}
@Overridepublic List finds(int index, intoffset) {//TODO Auto-generated method stub
return this.session.query(null, null, offset, index);
}
}
8. Test
public class MongoDBTest {
private static MongoTemplate template1;
private static MongoTemplate template2;
private static MongoTemplate template3;
private static Dao dao1;
private static Dao dao2;
private static Dao dao3;
static {
MongoObject mongoObject = new MongoObject();
mongoObject.setPort(12345);
MongoDB demo1 = new MongoDB(mongoObject, "demo1");
MongoDB demo2 = new MongoDB(mongoObject, "demo2");
MongoDB demo3 = new MongoDB(mongoObject, "demo3");
template1 = new MongoTemplate(demo1);
template2 = new MongoTemplate(demo2);
template3 = new MongoTemplate(demo3);
dao1 = new DaoImpl(template1, "MidStu");
dao2 = new DaoImpl(template2, "MidStu");
dao3 = new DaoImpl(template3, "MidStu");
}
@Test
public void save() {
MidStu midStu = new MidStu();
midStu.setHabit("zuqiu");
midStu.setId("saflfgsddsf35");
dao1.save(midStu);
MidStu midStuFind = new MidStu();
midStuFind.setId("saflfgsddsf35");
System.out.println(dao1.find(midStuFind).toString());
dao2.save(midStu);
System.out.println(dao2.find(midStuFind).toString());
dao3.save(midStu);
System.out.println(dao3.find(midStuFind).toString());
}
}