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 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 getPropertyMappings() {
		return propertyMappings;
	}
	public void setPropertyMappings(List propertyMappings) {
		this.propertyMappings = propertyMappings;
	}
	
}


/**
 * @author 
 * @version 创建时间:2017年3月23日 上午11:16:57
 * @description 扫描注解封装到ProperMapping
 */
public abstract class AnnotationScan implements Comparable> {
	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 getMappings() {
		List lists = new ArrayList();
		PropertyMapping mapping = getFieldByAnnotion(((Class) get_type()),Collection.class);
		PropertyMapping amapping = getFieldByAnnotion(((Class) 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 annotion) {
		Class clazz = null;
		Field[] fields = t.getDeclaredFields();
		PropertyMapping mapping = null;
		for (Field field : fields) {
			if (field.isAnnotationPresent(annotion)) {
				List 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 getPropertyMappings(String[] sfields) {
		List list = new ArrayList();
		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 lists = new ArrayList();
		for (Field field : fields) {
			lists.add(field.getName());
		}
		return lists.toArray(new String[lists.size()]);
	}
	@Override
	public int compareTo(AnnotationScan o) {
		return 0;
	}
	/*public static void main(String[] args) {
		AnnotationScan annotationScan = new AnnotationScan(){};
		List lists;
		try {
			lists = annotationScan.getMappings();
			System.out.println(lists);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}*/
}


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


			for (E e : sourceList) {
				pvalue = getValue(id, e).toString();
				if (!maps.containsKey(pvalue)) {
					targetObject = (T) ((Class>)annotationScan.get_type()).newInstance();
					BeanUtils.copyProperties(e, targetObject);
					// composites = new ArrayList();
					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  List setComposites(List composites, E obj, List propertyMappings) {
		String javaType;
		T object;
		List 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   void setData(T targetObject, E e, List propertyMappings) {
		String property;
		String javaType;
		Object value;
		Object object;
		// Object nestObject;
		List 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();
							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 list) {
		String property;
		Object value;
		for (PropertyMapping mapping : list) {
			property = mapping.getProperty();
			value = getValue(property, obj);

			setValue(value, property, nestObject);
		}
	}

	private  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;
	}
	
	
	
}


 

                            
                        
                    
                    
                    

你可能感兴趣的:(java)