一、首先自定义两个注解,分别是表名映射注解和字段名映射注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
//表明映射注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface TableName{
String value();
}
//属性映射注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface FieldName{
String name();
int length() default 0;
}
二、定义表对应的实体类
@TableName("student_info")
public class Student {
@FieldName(name="id",length=10)
private String id;
@FieldName(name="user_name")
private String userName;
@FieldName(name="user_age")
private String userAge;
}
三、使用实体类注解拼成查询sql
import java.lang.reflect.Field;
public class Main1 {
public static String createSql() throws ClassNotFoundException{
StringBuffer sqlBuffer = new StringBuffer();
sqlBuffer.append("select ");
Class<?> clas= Class.forName("spring.Student");
/*
* 获取属性注解值即字段名
*/
Field[] declaredFields = clas.getDeclaredFields();
String[] field = new String[declaredFields.length];
for(int i = 0;i<declaredFields.length;i++){
FieldName annotation2 = declaredFields[i].getAnnotation(FieldName.class);
field[i]=annotation2.name();
sqlBuffer.append(annotation2.name());
if(i<declaredFields.length-1){
sqlBuffer.append(",");
}
}
/*
* 获取类注解值表名
*/
TableName annotation = clas.getAnnotation(TableName.class);
String tableName = "";//表名
if(null != annotation){
tableName = annotation.value();
}
sqlBuffer.append(" from "+tableName);
return sqlBuffer.toString();
}
public static void main(String[] args) throws ClassNotFoundException {
System.out.println(createSql());
}
}