import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
public class BasicDBObjectUtil {
private BasicDBObjectUtil() {
}
/**
* 将Bean转换为BasicDBObject对象
*
* @param beanObj
* Bean对象
* @return BasicDBObject对象
*/
private static BasicDBObject getDBObjFromJavaBean(Object beanObj) {
BasicDBObject doc = null;
try {
doc = new BasicDBObject();
Field[] methodList = beanObj.getClass().getDeclaredFields();
for (int i = 0; i < methodList.length; i++) {
Field field = methodList[i];
field.setAccessible(true);
Object value = field.get(beanObj);
if (value != null) {
if (value instanceof String) {
if (!"".equals(value)) {
doc.put(field.getName(), field.get(beanObj));
}
} else {
doc.put(field.getName(), field.get(beanObj));
}
}
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
doc = null;
} catch (IllegalAccessException e) {
e.printStackTrace();
doc = null;
}
return doc;
}
public static DBObject getDBObject(Object beanObj) {
return getDBObjFromJavaBean(beanObj);
}
public static List<DBObject> getDBObjectList(List<Object> beanList) {
List<DBObject> basicDBOList = new ArrayList<DBObject>();
if (beanList != null && beanList.size() != 0) {
for (Object bean : beanList) {
basicDBOList.add(getDBObjFromJavaBean(bean));
}
}
return basicDBOList;
}
}
Bean 与 MongoDB
最新推荐文章于 2024-06-21 09:30:18 发布