手写mybatis,根据注解生成mysql执行语句
通过jvm中的反射,在创建实体类的对象时候,获取到实体类上的属性的注解,从而动态的拼接成需要执行的sql语句
1.@SetProperty
定义属性注解,value
定义实体中的属性对应数据库中的字段
@Retention(RetentionPolicy.RUNTIME)
public @interface SetProperty {
String value();
int length();
}
2.@SetTable
定义表名注解,value
对应数据库表名
@Target(value = {ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface SetTable {
String value();
}
3.添加有注解的实体
@SetTable(value = "it_user")
public class User {
@SetProperty(value = "it_id", length = 10)
private int id;
@SetProperty(value = "it_name", length = 10)
private String name;
public User() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + "]";
}
}
4.生成sql的执行语句
import java.lang.reflect.Field;
public class AnnotaionDemo01 {
public static void main(String[] args) throws Exception {
Class<?> userClass = Class.forName("cn.zwc.json.anno.User");
StringBuffer sb = new StringBuffer();
sb.append(" select ");
// 获取当前的所有的属性
Field[] declaredFields = userClass.getDeclaredFields();
for(int i = 0; i < declaredFields.length;i++){
Field field = declaredFields[i];
// 获取到这个字段上的注解
SetProperty proPertyAnnota = field.getDeclaredAnnotation(SetProperty.class);
String proPertyName = proPertyAnnota.value();
sb.append(" " + proPertyName);
if (i < declaredFields.length - 1) {
sb.append(" , ");
}
}
SetTable tableAnnota = userClass.getDeclaredAnnotation(SetTable.class);
// 表的名称
String tableName = tableAnnota.value();
sb.append(" from " + tableName);
System.out.println(sb.toString());
}
}
5.执行结果
select it_id , it_name from it_user