天天看点

自动生成mybatis中resultMap结果集     注意:这种方法仅适用于加了@Column注解的实体类

       上一篇文章提到,自己在新建表时如果表列特别多比如100多个字段时,mybatis中写公共查询字段baseColumn 或者resultMap时特别麻烦,用的是创建表时的sql脚本摘出来某些字段进行操作,但是并不是每次都会有现成的脚本供我们使用,因此我在原有的基础上进行了改良,将entity实体类,通过反射的技术将属性和列名获取到,拼接成resultMap的项。

     注意:这种方法仅适用于加了@Column注解的实体类

1.首先你的实体类得是加了列注解的,比如:

package entity;

import javax.persistence.Column;

public class Animal {

	@Column(name="ANIMAL_NAME")
	private String AnimalName;
	
	@Column(name="ANIAL_AGE")
	private String AnimalAge;
	
	public String getAnimalName() {
		return AnimalName;
	}
	public void setAnimalName(String animalName) {
		AnimalName = animalName;
	}
	public String getAnimalAge() {
		return AnimalAge;
	}
	public void setAnimalAge(String animalAge) {
		AnimalAge = animalAge;
	}
	public Animal() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Animal(String animalName, String animalAge) {
		super();
		AnimalName = animalName;
		AnimalAge = animalAge;
	}
	@Override
	public String toString() {
		return "Animal [AnimalName=" + AnimalName + ", AnimalAge=" + AnimalAge + "]";
	}
	
	
}
           

2.我封装了一个model用来将需要的列数据进行保存;

package test.zytest;

public class ResultMapModel {

	private String attribute ; //entity中属性的名称
	
	private String column;  //表中的类名
	
	private String columType;  //jdbctype类型
	
	private int level;  //所在类的级别,最基础为0,父类为1,祖父类2.。。以此类推

	public String getAttribute() {
		return attribute;
	}

	public void setAttribute(String attribute) {
		this.attribute = attribute;
	}

	public String getColumn() {
		return column;
	}

	public void setColumn(String column) {
		this.column = column;
	}

	public String getColumType() {
		return columType;
	}

	public void setColumType(String columType) {
		this.columType = columType;
	}

	public int getLevel() {
		return level;
	}

	public void setLevel(int level) {
		this.level = level;
	}
	
}
           

3.最主要的代码要来了,先说说思想吧,先通过一个类找到他的所有属性,然后再找他的父类直到得到Object.class;

通过字符串拆分获取到属性的名称和类型以及当前类的级别,同一级别的属性值相同;

public class PostConnectionTest {
	 private static Logger logger = Logger.getLogger(PostConnectionTest.class);

	    public static void main(String[] args) {
	    	String programFix = "entity"; //包前缀
	    	Object model = new Animal();
	    	List<ResultMapModel> reflex2 = getAttributeByReflex(model,programFix);
	    	for (ResultMapModel m : reflex2) {
				System.out.println("<result column=\""+m.getColumn()+"\" property=\""+
						m.getAttribute()+"\" jdbcType=\""+m.getColumType()+"\" />");
			}
	    }
	    private static List<ResultMapModel> getAttributeByReflex(Object object,String programFix) {
			Field[] fields = null;
			List<ResultMapModel> results = new ArrayList<ResultMapModel>();
			int count = 0;
			//通过反射查询其父类
			for(Class<?> clazz = object.getClass();clazz!=Object.class;clazz = clazz.getSuperclass()){
				//获取到该类下所有的属性
				fields = clazz.getDeclaredFields();
				for (Field field : fields) {
					//对field进行拆分处理   private java.lang.String Entity.Animal.AnimalName
					ResultMapModel result = new ResultMapModel();
					String[] split = field.toString().split(" ");
					for (int i = 0; i < split.length; i++) {
						if(split[i].startsWith(programFix)){
							String[] split2 = split[i].split("\\.");
							String string = split2[split2.length-1];
							//获取到最后一个项,并且把当前类下的属性值都设为同一个
							result.setAttribute(string);
							result.setLevel(count);
						}
					}
					//获取field的类型
					//Class<?> type = field.getType();可以直接通过自带的type方法获取属性类型
					String[] types = split[1].split("\\.");
					String strType = types[types.length-1]; //获取当前属性的类型
					if("long".equals(strType)||"Integer".equals(strType)||"int".equals(strType)){ 
						result.setColumType("DECIMAL");
					}else if("String".equals(strType)){
						result.setColumType("VARCHAR");
					}else if("Date".equals(strType)){
						result.setColumType("TIMESTAMP");
					}
					results.add(result);
				}
				count++;
			}
			List<ResultMapModel> list = getCoumnByReflex(object,results);
			return list;
		}
	    private static List<ResultMapModel> getCoumnByReflex(Object object,List<ResultMapModel> model) {
	    	
	    	List<String> list = new ArrayList<String>();
	    	int count = 0;
	    	for(Class<?> clazz = object.getClass();clazz!=Object.class;clazz = clazz.getSuperclass()){
	    		Field field;
	    		try {
	    			for(ResultMapModel mapModel : model){
	    				if(mapModel!=null && count == mapModel.getLevel()){
	    					field = clazz.getDeclaredField(mapModel.getAttribute());
	    					//通过获取注解信息得到数据库列信息
	    					Column column = field.getAnnotation(Column.class); 
	    					if(column == null){
	    						continue;
	    					}
	    					String name = column.name();
	    					mapModel.setColumn(name);
	    				}
	    			}
	    			count++;
	    		} catch (Exception e) {
	    			e.printStackTrace();
	    		} 
	    	}
	    	return model;
	    }
}
           

4.得到的结果如下:

自动生成mybatis中resultMap结果集     注意:这种方法仅适用于加了@Column注解的实体类

 基本上可以把最普通的结果集加上去了,至于id嘛,自己写!!!

如果有什么问题,可以评论告诉我!毕竟菜鸟,还望体谅!

继续阅读