java操作mongodb时,对象bean和DBObject相互转换的方法(推荐)
程序员文章站
2024-03-12 14:18:20
如下所示:
package com.iqbon.spider.util;
import java.lang.reflect.field;
impor...
如下所示:
package com.iqbon.spider.util; import java.lang.reflect.field; import java.lang.reflect.invocationtargetexception; import java.util.date; import org.apache.commons.beanutils.beanutils; import com.mongodb.basicdbobject; import com.mongodb.dbobject; public class beanutil { /** * 把实体bean对象转换成dbobject * @param bean * @return * @throws illegalargumentexception * @throws illegalaccessexception */ public static <t> dbobject bean2dbobject(t bean) throws illegalargumentexception, illegalaccessexception { if (bean == null) { return null; } dbobject dbobject = new basicdbobject(); // 获取对象对应类中的所有属性域 field[] fields = bean.getclass().getdeclaredfields(); for (field field : fields) { // 获取属性名 string varname = field.getname(); // 修改访问控制权限 boolean accessflag = field.isaccessible(); if (!accessflag) { field.setaccessible(true); } object param = field.get(bean); if (param == null) { continue; } else if (param instanceof integer) {//判断变量的类型 int value = ((integer) param).intvalue(); dbobject.put(varname, value); } else if (param instanceof string) { string value = (string) param; dbobject.put(varname, value); } else if (param instanceof double) { double value = ((double) param).doublevalue(); dbobject.put(varname, value); } else if (param instanceof float) { float value = ((float) param).floatvalue(); dbobject.put(varname, value); } else if (param instanceof long) { long value = ((long) param).longvalue(); dbobject.put(varname, value); } else if (param instanceof boolean) { boolean value = ((boolean) param).booleanvalue(); dbobject.put(varname, value); } else if (param instanceof date) { date value = (date) param; dbobject.put(varname, value); } // 恢复访问控制权限 field.setaccessible(accessflag); } return dbobject; } /** * 把dbobject转换成bean对象 * @param dbobject * @param bean * @return * @throws illegalaccessexception * @throws invocationtargetexception * @throws nosuchmethodexception */ public static <t> t dbobject2bean(dbobject dbobject, t bean) throws illegalaccessexception, invocationtargetexception, nosuchmethodexception { if (bean == null) { return null; } field[] fields = bean.getclass().getdeclaredfields(); for (field field : fields) { string varname = field.getname(); object object = dbobject.get(varname); if (object != null) { beanutils.setproperty(bean, varname, object); } } return bean; } }
以上就是小编为大家带来的java操作mongodb时,对象bean和dbobject相互转换的方法(推荐)全部内容了,希望大家多多支持~