java操作mongodb时,对象bean和DBObject相互转换的方法(推荐)

时间:2022-02-20 04:47:41

如下所示:

java" id="highlighter_150120">
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
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相互转换的方法(推荐)全部内容了,希望大家多多支持服务器之家~