Java 自定义注解及注解读取解析--模拟框架生成SQL语句

假设们使用一张简单的表,结构如下:
在这里插入图片描述
定义注解:
表注解:

package com.xzlf.annotation;


import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 对象对应表名注解
 * @author xzlf
 *
 */
@Target(value = {ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface StudentTable {
	String value();
}

字段注解:
package com.xzlf.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 对象属性对应表字段注解
 * @author xzlf
 *
 */
@Target(value = {ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface StudentField {
	String columnName();
	String type();
	int length();
}

写个对象类并使用自动以注解:

package com.xzlf.annotation;

@StudentTable(value="tb_student")
public class Student {

	@StudentField(columnName = "id", type = "int", length = 10)
	private  int id;
	@StudentField(columnName = "sname", type = "varchar", length = 10)
	private String sname;
	@StudentField(columnName = "age", type = "int", length = 3)
	private int age;
	
	public Student() {
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getSname() {
		return sname;
	}

	public void setSname(String sname) {
		this.sname = sname;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}
	
	
}

使用反射读取注解并生成SQL语句:

package com.xzlf.annotation;

import java.lang.reflect.Field;

/**
 * 使用反射读取注解的信息,模拟框架生成SQL语句
 * 
 * @author xzlf
 *
 */
public class AnnotationApp {
	public static void main(String[] args) {
		// 需要拼接的SQL语句
		StringBuilder sb = new StringBuilder("create table ");
		try {
			Class<Student> clz = (Class<Student>) Class.forName("com.xzlf.annotation.Student");
			// 获取类的指定信息
			StudentTable stable = clz.getAnnotation(StudentTable.class);
			String tableName = stable.value();
			sb.append(tableName);
			// 获取类属性注解
			Field[] declaredFields = clz.getDeclaredFields();
			sb.append("(");
			for (Field field : declaredFields) {
				// 获取类属性注解
				StudentField annotation = field.getAnnotation(StudentField.class);
				String fieldSQLStr = annotation.columnName() + " " 
						+ annotation.type() + "("+annotation.length()+"),";
				//System.out.println(fieldSQLStr);
				sb.append(fieldSQLStr);
			}
			sb.setCharAt(sb.length() - 1, ')');
			
			System.out.println(sb);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

运行测试:
在这里插入图片描述
SQL语句生成了。

重视基础,才能走的更远。
原文地址:https://www.cnblogs.com/xzlf/p/12681514.html