一、首先自定義兩個註解,分別是表名映射註解和字段名映射註解
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());
}
}