Java学习者论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

手机号码,快捷登录

恭喜Java学习者论坛(https://www.javaxxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,购买链接:点击进入购买VIP会员
JAVA高级面试进阶视频教程Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程

Go语言视频零基础入门到精通

Java架构师3期(课件+源码)

Java开发全终端实战租房项目视频教程

SpringBoot2.X入门到高级使用教程

大数据培训第六期全套视频教程

深度学习(CNN RNN GAN)算法原理

Java亿级流量电商系统视频教程

互联网架构师视频教程

年薪50万Spark2.0从入门到精通

年薪50万!人工智能学习路线教程

年薪50万!大数据从入门到精通学习路线年薪50万!机器学习入门到精通视频教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程 MySQL入门到精通教程
查看: 273|回复: 0

[注解学习]利用注解生成SQL命令

[复制链接]
  • TA的每日心情
    开心
    2021-3-12 23:18
  • 签到天数: 2 天

    [LV.1]初来乍到

    发表于 2014-10-28 23:56:36 | 显示全部楼层 |阅读模式
    一、被注解了的javaBean类
    1. @DBTable(name = "MEMBER")
    2. public class Member {
    3.   @SQLString(30) String firstName;
    4.   @SQLString(50) String lastName;
    5.   @SQLInteger Integer age;
    6.   @SQLString(value = 30, constraints = @Constraints(primaryKey = true))  String handle;
    7.   static int memberCount;
    8.   public String getHandle() { return handle; }
    9.   public String getFirstName() { return firstName; }
    10.   public String getLastName() { return lastName; }
    11.   public String toString() { return handle; }
    12.   public Integer getAge() { return age; }
    13. } ///:~
    14. 二、自定义的注解
    15. import java.lang.annotation.*;
    16. //这个注解用于生成数据库表
    17. @Target(ElementType.TYPE) // 该注解用于类
    18. @Retention(RetentionPolicy.RUNTIME)//运行期也保留注解
    19. public @interface DBTable {
    20.   public String name() default "";
    21. } ///:~
    22. import java.lang.annotation.*;
    23. //该注解用于修饰JavaBean的域
    24. @Target(ElementType.FIELD)
    25. @Retention(RetentionPolicy.RUNTIME)
    26. public @interface SQLInteger {
    27.   String name() default "";
    28.   Constraints constraints() default @Constraints;
    29. } ///:~
    30. import java.lang.annotation.*;
    31. //该注解用于修饰JavaBean的域
    32. @Target(ElementType.FIELD)
    33. @Retention(RetentionPolicy.RUNTIME)
    34. public @interface SQLString {
    35.   int value() default 0;
    36.   String name() default "";
    37.   Constraints constraints() default @Constraints;
    38. } ///:~
    39. import java.lang.annotation.*;
    40. //该注解用于修饰JavaBean的域
    41. @Target(ElementType.FIELD)
    42. @Retention(RetentionPolicy.RUNTIME)
    43. public @interface Constraints {
    44.   boolean primaryKey() default false;
    45.   boolean allowNull() default true;
    46.   boolean unique() default false;
    47. } ///:~
    48. 三、处理类
    49. 下面的程序,从命令行传入一个类名并读取类文件,检查其上的数据库注解,然后生成用来创建数据库表的SQL命令.
    50. import java.lang.annotation.*;
    51. import java.lang.reflect.*;
    52. import java.util.*;
    53. public class TableCreator {
    54.   public static void main(String[] args) throws Exception {
    55.     if(args.length < 1) {
    56.       System.out.println("arguments: annotated classes");
    57.       System.exit(0);
    58.     }
    59.     for(String className : args) {
    60.       Class< ? > cl = Class.forName(className);
    61.       DBTable dbTable = cl.getAnnotation(DBTable.class);
    62.       if(dbTable == null) {
    63.         System.out.println(
    64.           "No DBTable annotations in class " + className);
    65.         continue;
    66.       }
    67.       String tableName = dbTable.name();
    68.       // If the name is empty, use the Class name:
    69.       if(tableName.length() < 1)
    70.         tableName = cl.getName().toUpperCase();
    71.       List
    72.    
    73.       columnDefs = new ArrayList
    74.      
    75.       ();
    76.       for(Field field : cl.getDeclaredFields()) {
    77.         String columnName = null;
    78.         Annotation[] anns = field.getDeclaredAnnotations();
    79.         if(anns.length < 1)
    80.           continue; // Not a db table column
    81.         if(anns[0] instanceof SQLInteger) {
    82.           SQLInteger sInt = (SQLInteger) anns[0];
    83.           // Use field name if name not specified
    84.           if(sInt.name().length() < 1)
    85.             columnName = field.getName().toUpperCase();
    86.           else
    87.             columnName = sInt.name();
    88.           columnDefs.add(columnName + " INT" +
    89.             getConstraints(sInt.constraints()));
    90.         }
    91.         if(anns[0] instanceof SQLString) {
    92.           SQLString sString = (SQLString) anns[0];
    93.           // Use field name if name not specified.
    94.           if(sString.name().length() < 1)
    95.             columnName = field.getName().toUpperCase();
    96.           else
    97.             columnName = sString.name();
    98.           columnDefs.add(columnName + " VARCHAR(" +
    99.             sString.value() + ")" +
    100.             getConstraints(sString.constraints()));
    101.         }
    102.         StringBuilder createCommand = new StringBuilder(
    103.           "CREATE TABLE " + tableName + "(");
    104.         for(String columnDef : columnDefs)
    105.           createCommand.append("
    106.     " + columnDef + ",");
    107.         // Remove trailing comma
    108.         String tableCreate = createCommand.substring(
    109.           0, createCommand.length() - 1) + ");";
    110.         System.out.println("Table Creation SQL for " +
    111.           className + " is :
    112. " + tableCreate);
    113.       }
    114.     }
    115.   }
    116.   private static String getConstraints(Constraints con) {
    117.     String constraints = "";
    118.     if(!con.allowNull())
    119.       constraints += " NOT NULL";
    120.     if(con.primaryKey())
    121.       constraints += " PRIMARY KEY";
    122.     if(con.unique())
    123.       constraints += " UNIQUE";
    124.     return constraints;
    125.   }
    126. }
    127. /* 运行结果:
    128. Table Creation SQL for annotations.database.Member is :
    129. CREATE TABLE MEMBER(
    130.     FIRSTNAME VARCHAR(30));
    131. Table Creation SQL for annotations.database.Member is :
    132. CREATE TABLE MEMBER(
    133.     FIRSTNAME VARCHAR(30),
    134.     LASTNAME VARCHAR(50));
    135. Table Creation SQL for annotations.database.Member is :
    136. CREATE TABLE MEMBER(
    137.     FIRSTNAME VARCHAR(30),
    138.     LASTNAME VARCHAR(50),
    139.     AGE INT);
    140. Table Creation SQL for annotations.database.Member is :
    141. CREATE TABLE MEMBER(
    142.     FIRSTNAME VARCHAR(30),
    143.     LASTNAME VARCHAR(50),
    144.     AGE INT,
    145.     HANDLE VARCHAR(30) PRIMARY KEY);
    146. *///:~
    147.      
    148.    
    复制代码



       
         
         
          
          

            
          

            
          
         
       

      


    源码下载:http://file.javaxxz.com/2014/10/28/235636640.zip
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|Java学习者论坛 ( 声明:本站资料整理自互联网,用于Java学习者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2025-2-26 01:56 , Processed in 0.338583 second(s), 35 queries .

    Powered by Discuz! X3.4

    © 2001-2017 Comsenz Inc.

    快速回复 返回顶部 返回列表