package com.paile.utils.beans; import java.beans.PropertyDescriptor; import java.sql.Timestamp; import java.util.List; import java.util.Set; import org.apache.commons.beanutils.PropertyUtilsBean; import com.mongodb.BasicDBList; import com.mongodb.BasicDBObject; import com.mongodb.DBObject; /*** * 由JavaBean 到mongoDB的DBObject对象的转换(不包含子对象和集合对象) * @author libo */ public class SimpleJavaBean2DBObject { /*** * 将普通Java对象属性复制到DBObject里面(不包含子对象和集合对象) * @param ogi 普通Java对象 *@return 返回DBObject对象 */ public static DBObject copyProperties(Object orig,DBObject dbObj)throws Exception{ if(orig==null){ throw new IllegalArgumentException("No object bean specified,or is null"); } PropertyUtilsBean pro = new PropertyUtilsBean(); PropertyDescriptor[] origDescriptors = pro.getPropertyDescriptors(orig.getClass()); for (int i = 0; i < origDescriptors.length; i++) { PropertyDescriptor pdesc = origDescriptors[i]; String name = pdesc.getName(); if ("class".equals(name)) { continue; // No point in trying to set an object's class }; if (pro.isReadable(orig, name)){ Class<?> t = pdesc.getPropertyType(); boolean isPrimitive = MyBeanUtils.isPrimitiveType(t); if(isPrimitive){ //基础类型(8大类型+String) Object value = pro.getSimpleProperty(orig, name); dbObj.put(name, value); }else if(t == Timestamp.class){ Object value = pro.getSimpleProperty(orig, name); dbObj.put(name, value); }else{ Object value = pro.getSimpleProperty(orig, name); if(t.isAssignableFrom(List.class) ||t.isAssignableFrom(Set.class)){ if(value!=null){ List list = (List)value; if(list.isEmpty()) continue; BasicDBList dbList = new BasicDBList(); for(int j = 0;j<list.size();j++){ Object object = list.get(j); DBObject db = new BasicDBObject(); if(object!=null) copyProperties(object, db); dbList.add(db); } dbObj.put(name, dbList); } }else{ DBObject db = new BasicDBObject(); if(value!=null) copyProperties(value, db ); dbObj.put(name, db); } } } } return null; } }
JavaBean对象转DBOBject对象
猜你喜欢
转载自littie1987.iteye.com/blog/2193130
今日推荐
周排行