package com.zenfery.example.annotation.clazz;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import com.zenfery.example.annotation.sql.Constraint;
import com.zenfery.example.annotation.sql.TableColumnSQL;
import com.zenfery.example.annotation.sql.TableSQL;
public class TableSQLHandler {
/**
* 注解处理器:读取User类中注解,生成对应的SQL并打印出来
* 在此假设表的所有字段均为varchar(10)
* @since JDK 1.6
* @param args
*/
public static void main(String[] args) {
/**
* 注解的@Retention均为JVM保留注解(RetentionPolicy.RUNTIME)
* ,在此直接使用main方法启动JVM,通过Java提供的反射机制来处
* 理。
*/
try {
//指定在JVM需要处理注解的类
Class userClass = null ;
//userClass = Class.forName("com.zenfery.example.annotation.clazz.User");
userClass = User. class ;
//打印所有类的注解
Annotation[] annotations = userClass.getDeclaredAnnotations();
for ( int i= 0 ; i<annotations.length; i++){
System.out.println( "注解[" +(i+ 1 )+ "] = " +annotations[i].toString());
}
//检查类是否有@TableSQL注解
if ( userClass.isAnnotationPresent(TableSQL. class ) ){
//sql
String sql = "\nCREATE TABLE " ;
//注解了TableSQL注解
TableSQL ts = (TableSQL)userClass.getAnnotation(TableSQL. class );
String tableName = ts.value();
if ( "" .equals(tableName)){ //如果获取的值为TableSQL的默认值,则使用类名来做为表名
tableName = userClass.getSimpleName().toLowerCase();
}
System.out.println( "获取" +userClass.getName()+ "对应的表名为:" +tableName);
sql += tableName + " ( \n" ;
//从User类的属性中获取需要与数据库映射的字段
Field[] fields = userClass.getDeclaredFields();
List<String> primaryKeys = new ArrayList<String>(); //存储主键
for ( int i= 0 ; i<fields.length; i++){
Field field = fields[i];
if ( field.isAnnotationPresent(TableColumnSQL. class ) ){
TableColumnSQL tcs = (TableColumnSQL)field.getAnnotation(TableColumnSQL. class );
String fieldName = tcs.value(); //表中的字段名
Constraint c = tcs.constraint(); //字段对应的约束
boolean allowNull = c.allowNull(); //是否可为空
boolean isPrimary = c.isPrimary(); //是否为主键
//拼接SQL
sql += "\t" + fieldName + " VARCHAR(10)" ;
if (!allowNull) sql += " NOT NULL" ; //不允许为空
if (i<fields.length- 1 ) sql+= ",\n" ;
//主键
if (isPrimary) primaryKeys.add(fieldName);
} else {
System.out.println( "字段" +field.getName()+ "未使用注解@TableColumnSQL!" );
}
}
if (primaryKeys.size()> 0 ){
StringBuilder keys = new StringBuilder();
for ( int k= 0 ; k<primaryKeys.size(); k++){
keys.append(primaryKeys.get(k));
if (k<primaryKeys.size()- 1 )keys.append( "," );
}
sql += ",\n\tPRIMARY KEY " +keys.toString();
}
sql += "\n) DEFAULT CHARSET=utf8" ;
// ====> 打印SQL
System.out.println( "生成的SQL:" +sql);
} else {
System.out.println( "警告:" +userClass.getName()+ "未使用@TableSQL注解!" );
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
|