利用java反射、注解及泛型模拟ORM实现

/**
 * org.crazystone.annotation
 *
 * Function: TODO 
 *
 *   ver     date      		author
 * ──────────────────────────────────
 *   		 2012-9-11 		zhangzenglun
 *
 * Copyright (c) 2012, TNT All Rights Reserved.
 */

package org.crazystone.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 
 * @author zhangzenglun
 * @version 1.0
 * @since v1.0
 * @Date 2012-9-11 下午2:06:08
 */

/**
 * @Retention用来声明注解的保留策略,有CLASS、RUNTIME和SOURCE这三种,分别表示注解保存在类文件、JVM运行时刻和源代码中。
 * 只有当声明为RUNTIME的时候,才能够在运行时刻通过反射API来获取到注解的信息。
 * 
 * @Target用来声明注解可以被添加在哪些类型的元素上,如类型、方法和域等
 */

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Table {
	String tableName();
}


/**
 * TableField.java
 * org.crazystone.annotation
 *
 * Function: TODO 
 *
 *   ver     date      		author
 * ──────────────────────────────────
 *   		 2012-9-11 		zhangzenglun
 *
 * Copyright (c) 2012, TNT All Rights Reserved.
 */

package org.crazystone.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * ClassName:TableField
 * 
 * @author zhangzenglun
 * @version 1.0
 * @since v1.0
 * @Date 2012-9-11 下午2:14:41
 */

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD,ElementType.METHOD})
public @interface TableField {
	public String name();

	public boolean isPrimaryKey() default false;
}


/**
 * User.java
 * org.crazystone.annotation
 *
 * Function: TODO 
 *
 *   ver     date      		author
 * ──────────────────────────────────
 *   		 2012-9-11 		zhangzenglun
 *
 * Copyright (c) 2012, TNT All Rights Reserved.
 */

package org.crazystone.annotation;

/**
 * ClassName:User
 * 
 * @author zhangzenglun
 * @version 1.0
 * @since v1.0
 * @Date 2012-9-11 下午2:01:06
 */

@Table(tableName = "user")
public class User {
	@TableField(name = "user_id", isPrimaryKey = true)
	private int userId;
	@TableField(name = "user_name")
	private String userName;
	@TableField(name = "user_age")
	private int age;

	public int getUserId() {
		return userId;
	}

	public void setUserId(int userId) {
		this.userId = userId;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

}


/**
 * BaseOrmSupport.java
 * org.crazystone.annotation
 *
 * Function: TODO 
 *
 *   ver     date      		author
 * ──────────────────────────────────
 *   		 2012-9-11 		zhangzenglun
 *
 * Copyright (c) 2012, TNT All Rights Reserved.
*/

package org.crazystone.annotation;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * ClassName:BaseOrmSupport
 *
 * @author   zhangzenglun
 * @version  1.0
 * @since    v1.0
 * @Date	 2012-9-11 下午3:27:00 
 */
public abstract  class BaseOrmSupport<T> {
	public  void save(T o){
		Class<? extends Object> entityClass = o.getClass();
    	StringBuffer sql = new StringBuffer();
    	
    	sql.append("insert into ");
    	
    	Table a = (Table)entityClass.getAnnotation(Table.class);
    	if (a!=null) {
    		sql.append(a.tableName());
    	} else {
    		sql.append(entityClass.getName().substring(entityClass.getName().lastIndexOf(".")+1));
    	}
    	
    	sql.append(" (");
    	
    	Field[] fields = entityClass.getDeclaredFields();
    	String temp = "";
    	StringBuffer valueSql = new StringBuffer();
    	for (Field f:fields) {
    		TableField tf = f.getAnnotation(TableField.class);
    	
    		//获得字段第一个字母大写 
    		String firstLetter = f.getName().substring(0,1).toUpperCase(); 
    		//转换成字段的get方法
    	    String getMethodName = "get"+firstLetter+f.getName().substring(1); 
			try {
				
				Method getMethod = entityClass.getMethod(getMethodName, new Class[] {});
				//这个对象字段get方法的值 
				Object value = getMethod.invoke(o, new Object[] {}); 
				
				if (f.getType().getName().equals(java.lang.String.class.getName())) {
					valueSql.append(temp+"'"+value+"'");
				} else {
					valueSql.append(temp+value);
				}
				
			} catch (Exception e) {
			}

    		if (tf != null) {
    			sql.append(temp+tf.name());
    		} else {
    			sql.append(temp+f.getName());
    		} 
    		temp = ",";
    	}
    	
    	sql.append(")values(");
    	sql.append(valueSql);
    	sql.append(")");
    	
    	System.out.println(sql.toString());
	}
}



/**
 * User.java
 * org.crazystone.annotation
 *
 * Function: TODO 
 *
 *   ver     date      		author
 * ──────────────────────────────────
 *   		 2012-9-11 		zhangzenglun
 *
 * Copyright (c) 2012, TNT All Rights Reserved.
 */

package org.crazystone.annotation;

/**
 * ClassName:User
 * 
 * @author zhangzenglun
 * @version 1.0
 * @since v1.0
 * @Date 2012-9-11 下午2:01:06
 */

public class UserDAO extends BaseOrmSupport<User>{

}


测试类
package org.crazystone.annotation;

import junit.framework.TestCase;

public class AppTest 
    extends TestCase
{

    public void testApp()
    {
    	User user = new User();
    	user.setAge(100);
    	user.setUserName("skylun");
    	user.setUserId(1);
    	
    	UserDAO userDao = new UserDAO();
    	userDao.save(user);
    }
    
}


测试输出结果:
insert into user (user_id,user_name,user_age)values(1,'skylun',100)

你可能感兴趣的:(注解,jvm,sql,orm,反射)