java操作mongodb时,对象bean和DBObject相互转换的方法(推荐)
如下所示:
packagecom.iqbon.spider.util; importjava.lang.reflect.Field; importjava.lang.reflect.InvocationTargetException; importjava.util.Date; importorg.apache.commons.beanutils.BeanUtils; importcom.mongodb.BasicDBObject; importcom.mongodb.DBObject; publicclassBeanUtil{ /** *把实体bean对象转换成DBObject *@parambean *@return *@throwsIllegalArgumentException *@throwsIllegalAccessException */ publicstatic<T>DBObjectbean2DBObject(Tbean)throwsIllegalArgumentException, IllegalAccessException{ if(bean==null){ returnnull; } DBObjectdbObject=newBasicDBObject(); //获取对象对应类中的所有属性域 Field[]fields=bean.getClass().getDeclaredFields(); for(Fieldfield:fields){ //获取属性名 StringvarName=field.getName(); //修改访问控制权限 booleanaccessFlag=field.isAccessible(); if(!accessFlag){ field.setAccessible(true); } Objectparam=field.get(bean); if(param==null){ continue; }elseif(paraminstanceofInteger){//判断变量的类型 intvalue=((Integer)param).intValue(); dbObject.put(varName,value); }elseif(paraminstanceofString){ Stringvalue=(String)param; dbObject.put(varName,value); }elseif(paraminstanceofDouble){ doublevalue=((Double)param).doubleValue(); dbObject.put(varName,value); }elseif(paraminstanceofFloat){ floatvalue=((Float)param).floatValue(); dbObject.put(varName,value); }elseif(paraminstanceofLong){ longvalue=((Long)param).longValue(); dbObject.put(varName,value); }elseif(paraminstanceofBoolean){ booleanvalue=((Boolean)param).booleanValue(); dbObject.put(varName,value); }elseif(paraminstanceofDate){ Datevalue=(Date)param; dbObject.put(varName,value); } //恢复访问控制权限 field.setAccessible(accessFlag); } returndbObject; } /** *把DBObject转换成bean对象 *@paramdbObject *@parambean *@return *@throwsIllegalAccessException *@throwsInvocationTargetException *@throwsNoSuchMethodException */ publicstatic<T>TdbObject2Bean(DBObjectdbObject,Tbean)throwsIllegalAccessException, InvocationTargetException,NoSuchMethodException{ if(bean==null){ returnnull; } Field[]fields=bean.getClass().getDeclaredFields(); for(Fieldfield:fields){ StringvarName=field.getName(); Objectobject=dbObject.get(varName); if(object!=null){ BeanUtils.setProperty(bean,varName,object); } } returnbean; } }
以上就是小编为大家带来的java操作mongodb时,对象bean和DBObject相互转换的方法(推荐)全部内容了,希望大家多多支持毛票票~