java 使用注解完成类和表结构的映射关系

需求:

 使用注解完成类和表结构的映射关系,

表名为:tb_student

表结构:

id int(10)

name varchar(10)

age int(3)

自定义注解类Table ,注解表名

package study_09;

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(value=RetentionPolicy.RUNTIME)
public @interface Table {
	String value();//只有一个参数建议起名value
}

自定义注解类StudentField,注解属性

package study_09;

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(value=RetentionPolicy.RUNTIME)
public @interface StudentField {
	String columnName();//表格字段名
	String type();//字段类型
	int length();//字段长度
}

student类

package study_09;


@Table(value="tb_student")//设定表名
public class Student {
	@StudentField(columnName="sname",length=10,type="varchar")//设定字段的属性
	private String studentName;
	
	@StudentField(columnName="age",length=3,type="int")
	private int age;
	
	@StudentField(columnName="id",length=10,type="int")
	private int id;

	public String getStudentName() {
		return studentName;
	}

	public void setStudentName(String studentName) {
		this.studentName = studentName;
	}

	public int getAge() {
		return age;
	}

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

	public int getId() {
		return id;
	}

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

	
	
}

现在注解完毕,开始使用反射读取注解信息

package study_09;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;

public class Reflect01 {
	public static void main(String[] args) throws NoSuchFieldException, SecurityException {
		try {
			Class clz = Class.forName("study_09.Student");
			
			//获得这个类的所有注解
			Annotation[] annotations = clz.getAnnotations();
			for (Annotation annotation : annotations) {
				System.out.println(annotation);
			}
			//获得类的指定注解
			Table st = (Table)clz.getAnnotation(Table.class);
			System.out.println(st.value());
			
			//获得类的属性注解
			Field field = clz.getDeclaredField("studentName");//获取指定的字段
			StudentField stField = field.getAnnotation(StudentField.class);
			System.out.println(stField.columnName() + "------->" + stField.length() + "------>" + stField.type());//获取属性
			
			//根据获得表名和字段信息拼出SQL语句
			
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
@study_09.Table(value=tb_student)
tb_student
sname------->10------>varchar

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值