ORM框架
ORM : 对象关系映射
简而言之,实体类与数据库表字段的一一对应
我们要做的工作:使用注解来实现实体类与表的映射,并且使用反射技术生成Sql语句
代码实现
1、定义表名的注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface SetTable {
String table();
}
2、定义属性名的注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SetProperty {
String value();
}
3、定义User实体类
@SetTable(table="user")
public class User {
@SetProperty(value="user_id")
private int id;
@SetProperty(value="user_name")
private String name;
@SetProperty(value="user_age")
private int age;
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;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
4、根据实体类中的注解,使用反射来生成查询sql语句
public class OrmDemo {
public static void main(String[] args) throws ClassNotFoundException {
//加载User类文件
Class<User> clazz = (Class<User>) Class.forName("cn.zyyx.demo.User");
//从类对象中获取到类上面的注解
SetTable table = clazz.getAnnotation(SetTable.class);
//获取到表名
String tableName = table.table();
//使用StringBuffer拼接字符串
StringBuffer sb = new StringBuffer();
sb.append("select ");
//获取当前类的注解中的所有属性
Field[] fields = clazz.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
//获得属性对象
Field field = fields[i];
//获得属性对象上面的注解
SetProperty property = field.getAnnotation(SetProperty.class);
//获得注解中的value
String value = property.value();
sb.append(value);
if(i == fields.length - 1){
sb.append(" from ");
}else{
sb.append(",");
}
}
//拼接表名
sb.append(tableName);
System.out.println(sb.toString());
}
}
输出结果