java从数据库中查出来二次封装基于注解

实现类似于mybatis一对多关系和一对一关系:

上代码:
/**
 * @author 
 * @version 创建时间:2017年3月23日 上午11:01:39
 * @description 定义1对多关系注解 value代表要发射的字段名
 */
@Target({ ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Association {
	String[] value() default {};
}

/** 
* @author 
* @version 创建时间:2017年3月22日 下午4:23:00 
* @description 定义1对多关系注解 value代表要发射的字段名
*/
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Collection {
	String[] value() default {};
}

/** 
* @author 
* @version 创建时间:2017年3月23日 上午11:09:12 
* @description 封装注解对应的实体类中要反射的字段
*/
public class PropertyMapping {
	private String property;
	private String javaType;
	private List<PropertyMapping> propertyMappings;
	public String getProperty() {
		return property;
	}
	public void setProperty(String property) {
		this.property = property;
	}
	public String getJavaType() {
		return javaType;
	}
	public void setJavaType(String javaType) {
		this.javaType = javaType;
	}
	public List<PropertyMapping> getPropertyMappings() {
		return propertyMappings;
	}
	public void setPropertyMappings(List<PropertyMapping> propertyMappings) {
		this.propertyMappings = propertyMappings;
	}
	
}


/**
 * @author 
 * @version 创建时间:2017年3月23日 上午11:16:57
 * @description 扫描注解封装到ProperMapping
 */
public abstract class AnnotationScan<T> implements Comparable<AnnotationScan<T>> {
	Type _type;
	private boolean nest;
	
	public AnnotationScan() {
		Type superClass = getClass().getGenericSuperclass();// 获取该类的直接超类
		_type = ((ParameterizedType) superClass).getActualTypeArguments()[0];
	}

	public Type get_type() {
		return _type;
	}
	
	public boolean isNest() {
		return nest;
	}

	public List<PropertyMapping> getMappings() {
		List<PropertyMapping> lists = new ArrayList<PropertyMapping>();
		PropertyMapping mapping = getFieldByAnnotion(((Class<? extends AnnotationScan>) get_type()),Collection.class);
		PropertyMapping amapping = getFieldByAnnotion(((Class<? extends AnnotationScan>) get_type()),Association.class);
		if(mapping!=null){
			lists.add(mapping);
			nest = true;
		}
		if(amapping!=null){
			lists.add(amapping);
		}
		return lists;
	}
	
	private PropertyMapping getFieldByAnnotion(Class<?> t, Class<? extends Annotation> annotion) {
		Class<?> clazz = null;
		Field[] fields = t.getDeclaredFields();
		PropertyMapping mapping = null;
		for (Field field : fields) {
			if (field.isAnnotationPresent(annotion)) {
				List<PropertyMapping> mmappings = null;
				Annotation annotation = field.getAnnotation(annotion);
				String[] sfields = null;
				if (annotation instanceof Collection) {
					clazz = (Class<?>) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0];
					Collection collection = (Collection) annotation;
					sfields = collection.value();
				} else if (annotation instanceof Association) {
					clazz = field.getType();
					Association association = (Association) annotation;
					sfields = association.value();
				}
				if (sfields == null || sfields.length == 0) {
					sfields = getAllFields(clazz);
				}
				mmappings = getPropertyMappings(sfields);
				mapping = new PropertyMapping();
				mapping.setJavaType(clazz.getName());
				mapping.setProperty(field.getName());
				mapping.setPropertyMappings(mmappings);
			}
		}
		return mapping;
	}

	private List<PropertyMapping> getPropertyMappings(String[] sfields) {
		List<PropertyMapping> list = new ArrayList<PropertyMapping>();
		PropertyMapping mapping;
		for (String s : sfields) {
			mapping = new PropertyMapping();
			mapping.setProperty(s);
			list.add(mapping);
		}
		return list;
	}

	private String[] getAllFields(Class nestClass) {
		Field[] fields = nestClass.getDeclaredFields();
		List<String> lists = new ArrayList<String>();
		for (Field field : fields) {
			lists.add(field.getName());
		}
		return lists.toArray(new String[lists.size()]);
	}
	@Override
	public int compareTo(AnnotationScan<T> o) {
		return 0;
	}
	/*public static void main(String[] args) {
		AnnotationScan<ProductDetailEntity> annotationScan = new AnnotationScan<ProductDetailEntity>(){};
		List<PropertyMapping> lists;
		try {
			lists = annotationScan.getMappings();
			System.out.println(lists);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}*/
}


/**
 * @author 
 * @version 创建时间:2017年3月22日 下午3:39:01
 * @param <T>
 * @param <E>
 * @description 封装数据
 */
public  class AnnotionMapping<T> {
	private AnnotationScan<T> annotationScan;
	private Map<String, List<Object>> maps = new HashMap<String, List<Object>>();
	private String id;
	public AnnotionMapping(AnnotationScan<T> annotationScan,String id){
		this.annotationScan = annotationScan;
		this.id = id;
	}
	
	public  <E> List<T> getBeans(List<E> sourceList) {
		
		List<T> targerObjects = new ArrayList<T>();
		
		List<PropertyMapping> propertyMappings = annotationScan.getMappings();
		
		try {
			
			String pvalue;
			
			List<T> dataList = new ArrayList<T>();
			T targetObject = null;
			List<Object> composites;


			for (E e : sourceList) {
				pvalue = getValue(id, e).toString();
				if (!maps.containsKey(pvalue)) {
					targetObject = (T) ((Class<? extends AnnotationScan<T>>)annotationScan.get_type()).newInstance();
					BeanUtils.copyProperties(e, targetObject);
					// composites = new ArrayList<Object>();
					setData(targetObject, e, propertyMappings);
					// maps.put(getValue(id, t).toString(), composites);
					dataList.add(targetObject);
				} else if (annotationScan.isNest()) {
					composites = maps.get(pvalue);
					composites = setComposites(composites, e, propertyMappings);
				}
				/*
				 * else { composites = maps.get(getValue(id, t)); composites =
				 * setComposites(composites, t, resultSetMappings); }
				 */
			}

			return dataList;
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		return targerObjects;
	}

	private <E> List<Object> setComposites(List<Object> composites, E obj, List<PropertyMapping> propertyMappings) {
		String javaType;
		T object;
		List<PropertyMapping> compositesMappings;
		for (PropertyMapping mapping : propertyMappings) {
			javaType = mapping.getJavaType();
			if (javaType != null) {
				try {
					object = (T) Class.forName(javaType).newInstance();
					compositesMappings = mapping.getPropertyMappings();
					setData(object, obj, compositesMappings);
					composites.add(object);
					return composites;
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}

	private  <E> void setData(T targetObject, E e, List<PropertyMapping> propertyMappings) {
		String property;
		String javaType;
		Object value;
		Object object;
		// Object nestObject;
		List<Object> composites;
		for (PropertyMapping mapping : propertyMappings) {
			property = mapping.getProperty();
			javaType = mapping.getJavaType();
			if (javaType == null) {
				value = getValue(property, e);
				setValue(value, property, targetObject);
			} else {
				try {
					// nestObject = getValue(property, targetObject);
					Field field = targetObject.getClass().getDeclaredField(property);
					if (field.getType().isAssignableFrom(List.class)) {
						composites = maps.get(getValue(id, e));
						if (composites == null) {
							composites = new ArrayList<Object>();
							maps.put(getValue(id, e).toString(), composites);
						}
						composites = setComposites(composites, e, propertyMappings);
						setValue(composites, property, targetObject);
					} else {
						object = Class.forName(javaType).newInstance();
						setAssociation(object, e, mapping.getPropertyMappings());
						setValue(object, property, targetObject);
					}
				} catch (Exception e1) {
				}
			}
		}

	}

	private void setAssociation(Object nestObject, Object obj, List<PropertyMapping> list) {
		String property;
		Object value;
		for (PropertyMapping mapping : list) {
			property = mapping.getProperty();
			value = getValue(property, obj);

			setValue(value, property, nestObject);
		}
	}

	private <E> void setValue(Object value, String property, E obj) {
		try {
			Field field = obj.getClass().getDeclaredField(property);
			field.setAccessible(true);
			field.set(obj, value);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public Object getValue(String property, Object obj) {
		try {
			Field field = obj.getClass().getDeclaredField(property);
			field.setAccessible(true);
			return field.get(obj);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}
	
	
	
}


猜你喜欢

转载自chen-sai-201607223902.iteye.com/blog/2365024