模拟ORM( 对象关系映射 ), 利用注解和反射完成类和表结构的映射关系
类 | 表 |
---|---|
类名 | 表名 |
属性 | 表字段 |
一个类对象 | 表中的一条记录 |
完整示例代码:
package com.hz;
import com.sun.deploy.util.StringUtils;
import java.lang.annotation.*;
import java.lang.reflect.Field;
import java.util.Arrays;
@TableName("user") // 数据库中有一张名为User的表
public class User {
@DBField(name = "name", type = "NVARCHAR2", len = 50, nullable = false)//库中name字段
private String userName;
@DBField(name = "pwd", type = "NVARCHAR2", len = 100, nullable = false)//库中pwd字段
private String passWord;
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface TableName{
String value();
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface DBField{
String name();
String type();
int len();
boolean nullable();
}
class MyOrm{
public static void main(String[] args) throws Exception {
// sql有了就可以通过 jdbc来获取数据了
String sql = new MyOrm().getSelectSql();
System.out.println(sql);
}
private String getSelectSql() throws ClassNotFoundException {
Class clz = Class.forName("com.hz.User");
// // 获取所有注解
// Annotation[] annotations = clz.getAnnotations();
// for (Annotation annotation : annotations) {
// System.out.println(annotation);
// }
// 获取表名的注解
TableName annTable = (TableName) clz.getAnnotation(TableName.class);
// System.out.println(annTable.value());
// 获取字段的注解
Field[] declaredFields = clz.getDeclaredFields();
String[] fields = new String[declaredFields.length];
for (int i = 0; i < declaredFields.length; i++) {
Field declaredField = declaredFields[i];
// System.out.printf(" ===== %s ====\n", declaredField.getName());
DBField annField = declaredField.getAnnotation(DBField.class);
// System.out.println(annField.name());
// System.out.println(annField.type());
// System.out.println(annField.len());
// System.out.println(annField.nullable());
fields[i] = annField.name();
}
return String.format("select %s from %s",
StringUtils.join(Arrays.asList(fields), ","),
annTable.value());
}
}
结果:
select name,pwd from user
原文:https://www.cnblogs.com/icefoxhz/p/13680446.html