java가 mongodb를 조작할 때 대상 bean과 DBObject를 서로 변환하는 방법(추천)

3164 단어 mongodbdbobject
다음과 같습니다.

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; 
 } 
}
다음은 여러분께 가져온 자바가 몽고db를 조작할 때 대상 bean과 DBObject가 서로 전환하는 방법(추천)의 모든 내용입니다. 많은 응원 부탁드립니다~

좋은 웹페이지 즐겨찾기