新方式不支持map,还原

back_recharge
wangyuan 2019-01-07 15:16:42 +08:00
parent 94c6b35ac8
commit a5db8e814a
6 changed files with 444 additions and 15 deletions

View File

@ -0,0 +1,390 @@
package com.ljsd.common.mogodb;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import java.lang.reflect.*;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
public class BeanUtil {
private static Map<Class<?>, Field[]> fieldMap = new ConcurrentHashMap<>();
//是否是byte[]
private static boolean isByteArray(Object obj){
return obj instanceof byte[];
}
//是否是数组
private static boolean isArray(Object obj){
if(isByteArray(obj)){
return false;
}
return obj.getClass().isArray();
}
//将数组对象转为DBObject
private static DBObject array2DBObject(Object obj) throws IllegalAccessException {
Object[] arr = (Object[]) obj;
BasicDBList dbList = new BasicDBList();
for(int i=0; i<arr.length; i++){
Object dbObject = bean2DBObject(arr[i]);
dbList.add(dbObject);
}
return dbList;
}
//是否是list
private static boolean isList(Object obj){
return obj instanceof List;
}
//将list对象转为DBObject
private static DBObject list2DBObject(Object obj) throws IllegalAccessException {
List list = (List) obj;
BasicDBList dbList = new BasicDBList();
for(int i=0; i<list.size(); i++){
Object dbObject = bean2DBObject(list.get(i));
dbList.add(dbObject);
}
return dbList;
}
//是否是map对象
private static boolean isMap(Object obj){
return obj instanceof Map;
}
//将map对象转为DBObject
private static DBObject map2DBObject(Object obj) throws IllegalAccessException {
Map<Object, Object> map = (Map) obj;
DBObject dbObject = new BasicDBObject();
for (Map.Entry<Object, Object> entry : map.entrySet()) {
Object dbObject1 = bean2DBObject(entry.getValue());
dbObject.put(entry.getKey().toString(), dbObject1);
}
return dbObject;
}
//是否是集合对象
private static boolean isSet(Object obj){
return obj instanceof Set;
}
//将集合对象转为DBObject
private static DBObject set2DBObject(Object obj) throws IllegalAccessException {
Set<Object> set = (Set) obj;
BasicDBList dbList = new BasicDBList();
for(Object val: set){
Object dbObject = bean2DBObject(val);
dbList.add(dbObject);
}
return dbList;
}
private static <T> boolean isBaseType(T param){
if (param instanceof Integer) {//判断变量的类型
return true;
} else if (param instanceof String) {
return true;
} else if (param instanceof Double) {
return true;
} else if (param instanceof Float) {
return true;
} else if (param instanceof Long) {
return true;
} else if (param instanceof Boolean) {
return true;
} else if (param instanceof Date) {
return true;
} else if (param instanceof Byte) {
return true;
}
return false;
}
private static Field[] getFields(Class<?> clazz){
Field[] fields = fieldMap.get(clazz);
if(fields == null) {
fields = clazz.getDeclaredFields();
fieldMap.put(clazz, fields);
}
return fields;
}
public static <T> Object bean2DBObject(T bean) throws IllegalArgumentException,
IllegalAccessException {
if (bean == null) {
return null;
}
if(isBaseType(bean)){
return bean;
}
DBObject dbObject = new BasicDBObject();
if (isMap(bean)) {
return map2DBObject(bean);
} else if (isSet(bean)) {
return set2DBObject(bean);
} else if (isArray(bean)) {
return array2DBObject(bean);
} else if (isList(bean)) {
return list2DBObject(bean);
} else if (isByteArray(bean)) {
return dbObject;
}
// 获取对象对应类中的所有属性域
Class<?> clazz = bean.getClass();
while(clazz != null) {
Field[] fields = getFields(clazz);
for (Field field : fields) {
// 获取属性名
String varName = field.getName();
if(varName.startsWith("_")){
continue;
} else if(varName.equals("root")){
continue;
} else if (varName.equals("id")) {
varName = "_id";
}
// 修改访问控制权限
boolean accessFlag = field.isAccessible();
if (!accessFlag) {
field.setAccessible(true);
}
Object param = field.get(bean);
if (param == null) {
continue;
}
if (isBaseType(param)) {
dbObject.put(varName, param);
} else {
DBObject rdbObject = (DBObject) bean2DBObject(param);
dbObject.put(varName, rdbObject);
}
// 恢复访问控制权限
field.setAccessible(accessFlag);
}
clazz = clazz.getSuperclass();
}
return dbObject;
}
//从基础类型中取得值
private static Object getBaseObj(Object object, Class<?> clazz){
if(clazz == String.class){
return object;
}
if(clazz == int.class){
return object;
}
if(clazz == long.class){
return object;
}
if( clazz.equals(float.class)){
return ((Double)object).floatValue();
}
if(clazz == double.class){
return object;
}
if(clazz == byte.class){
return ((Integer)object).byteValue();
}
if(clazz == boolean.class){
return object;
}
if(clazz == Integer.class){
return object;
}
if(clazz == Long.class){
return object;
}
if( clazz.equals(Float.class)){
return ((Double)object).floatValue();
}
if(clazz == Double.class){
return object;
}
if(clazz == Byte.class){
return object;
}
if(clazz == Boolean.class){
return object;
}
return null;
}
//是否是map对象
private static boolean isMap(Class<?> clazz){
if( clazz == Map.class){
return true;
}
return false;
}
//取得key对应的值
private static Object getKey(String key, Class<?> clazz){
if(clazz == Integer.class){
return Integer.valueOf(key);
}
if(clazz == Long.class){
return Long.valueOf(key);
}
return key;
}
//将DBObject转为map
private static <K, V> Map<K, V> dbObject2Map(DBObject dbObject, Field field, MongoRoot root) throws Exception {
ParameterizedType pt = (ParameterizedType) field.getGenericType();
Type[] types = pt.getActualTypeArguments();
Map map = new HashMap<K, V>();
BasicDBObject dbObj = (BasicDBObject)dbObject;
for (Map.Entry<String, Object> entry : dbObj.entrySet()) {
Object obj = getObj(entry.getValue(), (Class)types[1], root);
// Object value = ((Class)types[1]).newInstance();
// Object obj = dbObject2Bean((DBObject) entry.getValue(), value, root);
Object key = getKey(entry.getKey(), (Class)types[0]);
map.put(key, obj);
}
return map;
}
//是否是集合对象
private static boolean isSet(Class<?> clazz){
if(clazz == Set.class){
return true;
}
return false;
}
//将dbobj转为普通对象
private static Object getObj(Object dbobj, Class<?> clazz, MongoRoot root) throws Exception {
Object obj = getBaseObj(dbobj, clazz);
if(obj == null){
Constructor constructor = clazz.getDeclaredConstructor();
boolean isAccessible = constructor.isAccessible();
constructor.setAccessible(true);
obj = constructor.newInstance();
constructor.setAccessible(isAccessible);
dbObject2Bean((DBObject) dbobj, obj, root);
}
return obj;
}
//将DBObject转为set
private static <T> Set<T> dbObject2Set(DBObject dbObject, Field field, MongoRoot root) throws Exception {
ParameterizedType pt = (ParameterizedType) field.getGenericType();
Type[] types = pt.getActualTypeArguments();
Set set = ConcurrentHashMap.<T> newKeySet();
BasicDBList dbList = (BasicDBList)dbObject;
for (Object dbobj : dbList) {
Object obj = getObj(dbobj, (Class)types[0], root);
set.add(obj);
}
return set;
}
//是否是byte[]
private static boolean isByteArray(Class<?> clazz){
return clazz == byte[].class;
}
//是否是数组
private static boolean isArray(Class<?> clazz){
if(isByteArray(clazz)){
return false;
}
return clazz.isArray();
}
//将DBObject转换为数组
private static Object[] dbObject2Array(DBObject dbObject, Class<?> clazz, MongoRoot root) throws Exception {
BasicDBList basicDBList = (BasicDBList)dbObject;
Object[] objs = (Object[])Array.newInstance(clazz.getComponentType(), basicDBList.size());
for(int i=0; i<basicDBList.size(); i++){
Object dbobj = (Object)basicDBList.get(i);
Object obj = getObj(dbobj, clazz.getComponentType(), root);
objs[i] = obj;
}
return objs;
}
//是否是list
private static boolean isList(Class<?> clazz){
if(clazz == List.class){
return true;
}
if(clazz == ArrayList.class){
return true;
}
if(clazz == CopyOnWriteArrayList.class){
return true;
}
return false;
}
//将DBObject转为list
private static <T> List<T> dbObject2List(DBObject dbObject, Field field, MongoRoot root) throws Exception {
ParameterizedType pt = (ParameterizedType) field.getGenericType();
Type[] types = pt.getActualTypeArguments();
List list = new CopyOnWriteArrayList<T>();
BasicDBList dbList = (BasicDBList)dbObject;
for (Object dbobj : dbList) {
Object obj = getObj(dbobj, (Class)types[0], root);
list.add(obj);
}
return list;
}
//DBObject转换为Bean对象
public static Object dbObject2Bean(DBObject dbObject, Object bean, MongoRoot root) throws Exception {
if (bean == null) {
return null;
}
Class<?> clazz = bean.getClass();
while (clazz != null) {
Field[] fields = getFields(clazz);
for (Field field : fields) {
String varName = field.getName();
Object object = null;
if (varName.equals("id")) {
object = dbObject.get("_id");
} else if(varName.equals("_root")){
((MongoBase)bean).setRoot((MongoRoot) root);
continue;
} else if(varName.equals("bsave")){
((MongoRoot)bean).setBsave(true);
continue;
} else {
object = dbObject.get(varName);
}
if (object == null) {
continue;
}
boolean accessFlag = field.isAccessible();
if (!accessFlag) {
field.setAccessible(true);
}
//System.out.println("varName=" + varName);
Class<?> fieldClazz = field.getType();
Object obj = getBaseObj(object, fieldClazz);
if (obj != null) {
field.set(bean, obj);
} else if (isMap(fieldClazz)) {
obj = dbObject2Map((DBObject) object, field, root);
} else if (isSet(fieldClazz)) {
obj = dbObject2Set((DBObject) object, field, root);
} else if (isArray(fieldClazz)) {
obj = dbObject2Array((DBObject) object, fieldClazz, root);
} else if (isList(fieldClazz)) {
obj = dbObject2List((DBObject) object, field, root);
} else if (isByteArray(fieldClazz)) {
obj = object;
} else {
obj = fieldClazz.newInstance();
obj = dbObject2Bean((DBObject) object, obj, root);
}
field.set(bean, obj);
// 恢复访问控制权限
field.setAccessible(accessFlag);
}
clazz = clazz.getSuperclass();
}
return bean;
}
public static <T> T dbObject2Bean(DBObject dbObject, Class<T> clazz) throws Exception {
if(dbObject == null){
return null;
}
T bean = clazz.newInstance();
dbObject2Bean(dbObject, bean, (MongoRoot)bean);
return bean;
}
}

View File

@ -5,6 +5,8 @@ import org.springframework.data.mongodb.core.MongoTemplate;
import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
@ -27,24 +29,19 @@ public class LjsdMongoTemplate {
}
public <T> List<T> findAll(String collectionName, Class<T> clazz) throws Exception {
List<T> all = mongoTemplate.findAll(clazz, collectionName);
if(all!=null && !all.isEmpty()){
T t = all.get(0);
if(t.getClass().getSuperclass() == MongoRoot.class){
for(T t1 : all){
dynamicChangeTheMongoRoot(t1, (MongoRoot) t1);
}
}
DBCollection coll = mongoTemplate.getCollection(collectionName);
DBCursor dbCursor = coll.find();
List<T> list= new ArrayList<>(dbCursor.count());
for (Iterator<DBObject> it = dbCursor.iterator(); it.hasNext(); ) {
list.add(BeanUtil.dbObject2Bean(it.next(), clazz));
}
return all;
return list;
}
public <T> T findById(String collectionName, String id, Class<T> clazz) throws Exception {
T result = mongoTemplate.findById(id, clazz, collectionName);
if(result.getClass().getSuperclass() == MongoRoot.class){
dynamicChangeTheMongoRoot(result,(MongoRoot) result);
}
return result;
DBCollection coll = mongoTemplate.getCollection(collectionName);
DBObject doc = coll.findOne(id.toString());
return BeanUtil.dbObject2Bean(doc, clazz);
}
public void chnage(Object obj){

View File

@ -2,6 +2,7 @@ package com.ljsd.common.mogodb.test;
import com.ljsd.common.mogodb.LjsdMongoTemplate;
import com.ljsd.common.mogodb.test.pojo.BaseInfoForTest;
import com.ljsd.common.mogodb.test.pojo.CardTestInfo;
import com.ljsd.common.mogodb.test.pojo.PlayerForTest;
import com.mongodb.MongoClientURI;
import org.springframework.data.mongodb.core.MongoTemplate;
@ -20,7 +21,7 @@ public class TestMongo {
try {
ljsdMongoTemplate = getLjsdMongoTemplate();
PlayerForTest.init(ljsdMongoTemplate);
//save();
// save();
PlayerForTest one = findOne();
update(one);
System.out.println();
@ -44,10 +45,14 @@ public class TestMongo {
}
public static void save() throws Exception {
CardTestInfo cardTestInfo = new CardTestInfo();
cardTestInfo.setId("33");
cardTestInfo.setLevel("555");
BaseInfoForTest baseInfoForTest = new BaseInfoForTest();
baseInfoForTest.setAge(10);
baseInfoForTest.setName("test");
PlayerForTest playerForTest = new PlayerForTest(1,baseInfoForTest);
baseInfoForTest.addCard(2,cardTestInfo);
ljsdMongoTemplate.save(playerForTest);
System.out.println(ljsdMongoTemplate);
}

View File

@ -10,9 +10,16 @@ public class BaseInfoForTest extends MongoBase {
private int age;
private Map<String,String> otherInfoMsg = new ConcurrentHashMap<>();
private Map<Integer,CardTestInfo> cardTestInfoMap;
public BaseInfoForTest(){
cardTestInfoMap = new ConcurrentHashMap<>();
}
public void addCard(int cardId,CardTestInfo cardTestInfo) throws Exception {
cardTestInfo.init(getRoot(),getMongoKey() + ".cardTestInfoMap." + cardId);
updateString("cardMap." +cardId, cardTestInfo);
cardTestInfoMap.put(cardId,cardTestInfo);
}
public String getName() {

View File

@ -0,0 +1,28 @@
package com.ljsd.common.mogodb.test.pojo;
import com.ljsd.common.mogodb.MongoBase;
public class CardTestInfo extends MongoBase {
private String id;
private String level;
public void setId(String id) throws Exception {
updateString("id",id);
this.id = id;
}
public void setLevel(String level) throws Exception {
updateString("level",level);
this.level = level;
}
public String getId() {
return id;
}
public String getLevel() {
return level;
}
}

View File

@ -3,6 +3,8 @@ package com.ljsd.common.mogodb.test.pojo;
import com.ljsd.common.mogodb.LjsdMongoTemplate;
import com.ljsd.common.mogodb.MongoRoot;
import java.util.Map;
public class PlayerForTest extends MongoRoot {
private final static String _COLLECTION_NAME = "play_test";
private BaseInfoForTest baseInfoForTest;