手写简单ORM框架

 1 package com.example.demo02.orm;
 2 
 3 import java.lang.annotation.*;
 4 import java.lang.reflect.Field;
 5 
 6 /**
 7  * 表映射
 8  */
 9 @Target(value = ElementType.TYPE)
10 @Retention(value = RetentionPolicy.RUNTIME)
11 @interface Table {
12     String tableName();
13 }
14 
15 /**
16  * 字段映射
17  */
18 @Target(value = ElementType.FIELD)
19 @Retention(value = RetentionPolicy.RUNTIME)
20 @interface Column {
21     String columnName();
22 }
23 
24 /**
25  * 实体
26  */
27 @Table(tableName = "user")
28 class User {
29 
30     @Column(columnName = "user_id")
31     private String userId;
32 
33     @Column(columnName = "user_name")
34     private String userName;
35 }
36 
37 /**
38  * 手写ORMDemo
39  */
40 
41 public class ORMDemo {
42     public static void main(String[] args) throws ClassNotFoundException {
43         Class<?> userClazz = Class.forName("com.example.demo02.orm.User");
44         Table declaredAnnotation = userClazz.getDeclaredAnnotation(Table.class);
45         String tableName = declaredAnnotation.tableName();
46         Field[] fields = userClazz.getDeclaredFields();
47         StringBuffer stringBuffer = new StringBuffer("select");
48         for (int i = 0 ;i < fields.length ;i++) {
49             stringBuffer.append(" "+ fields[i].getDeclaredAnnotation(Column.class).columnName());
50             if (i < fields.length - 1) {
51                 stringBuffer.append(" , ");
52             }
53         }
54 
55         stringBuffer.append(" from "+ tableName);
56 
57         System.out.println(stringBuffer.toString());
58     }
59 
60 }

 

posted on 2018-10-27 19:48  jovelove  阅读(291)  评论(0)    收藏  举报