【Java注解】自定义注解、与数据库结合使用
生活随笔
收集整理的這篇文章主要介紹了
【Java注解】自定义注解、与数据库结合使用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
注解的作用:可以對程序作出解釋、可以被其他程序讀取
自定義注解
定義注解、定義注解中包含的參數、參數的默認值。
案例一
定義注解
使用注解
案例二
如果注解中只有一個參數,通常將參數名稱定義為value。
定義注解
使用注解
- 只有一個參數時,11行的value可以省略
注解使用實戰(與數據庫相結合)
我們希望通過注解,將對象內容轉換為數據庫表時需要的額外信息做標注,通過Hibernate框架讀取類中的注解信息,生成sql語句,然后送到數據庫中執行
需要完成以下步驟:
- 定義注解
- 在類中使用注解
- 定義注解的解析程序,對注解進行解析處理(實際使用中,解析注解的步驟通常由框架寫好)
定義注解
@MyTable的定義
package cn.hanquan.annotation;import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target;@Target(value = { ElementType.TYPE }) // 用于修飾類型 @Retention(RetentionPolicy.RUNTIME) public @interface MyTable {String value(); }@MyField的定義
package cn.hanquan.annotation;import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target;@Target(value = { ElementType.FIELD }) // 用于修飾屬性 @Retention(RetentionPolicy.RUNTIME) public @interface MyField {String columnName();// 列名String type();// 類型int length();// 長度// 除此之外,還有...是否為空...等等,此處省略 }在類中使用注解
Student.java
package cn.hanquan.annotation;@MyTable("tb_student") public class Student {// 列名 類型 長度@MyField(columnName = "id", type = "int", length = 10)private int id;@MyField(columnName = "stuName", type = "varchar", length = 10)private String stuName;@MyField(columnName = "age", type = "int", length = 3)private int age;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getStuName() {return stuName;}public void setStuName(String stuName) {this.stuName = stuName;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}}定義注解的解析程序
通過第三方程序讀取指定類的相關信息,從而拼出相關的sql語句
package cn.hanquan.annotation;import java.lang.annotation.Annotation; import java.lang.reflect.Field;/* * 此 Demo 模擬一個第三方的程序* 使用反射讀取注解的信息,模擬處理注解信息的流程* * 通過第三方程序讀取指定類的相關信息,從而拼出相關的 sql 語句*/ public class Demo {public static void main(String[] args) {try {Class c = Class.forName("cn.hanquan.annotation.Student");// 獲取類// 獲得類的單個注解MyTable tb = (MyTable) c.getAnnotation(MyTable.class);System.out.println(tb.value());// 獲得類的所有注解Annotation[] annotations = c.getAnnotations();for (Annotation a : annotations) {System.out.println(a);}// 獲得類的屬性注解Field f = c.getDeclaredField("stuName");// 獲取屬性MyField myField = f.getAnnotation(MyField.class);// 獲取屬性的注解System.out.println(myField.columnName() + " " + myField.type() + " " + myField.length());// 根據獲得的表明、字段信息拼出DDL語句,使用JDBC執行這個SQL,在數據庫中生成相關的表(省略)} catch (Exception e) {e.printStackTrace();}} }總結
以上是生活随笔為你收集整理的【Java注解】自定义注解、与数据库结合使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Eclipse正确配置Tomcat之后仍
- 下一篇: 【C++鼠标键盘操作】自动下载CSDN博