栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

1.编写java框架的必备基础-反射读取自定义注解-简单体会orm-有对应视频教程-需要可找我领取

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

1.编写java框架的必备基础-反射读取自定义注解-简单体会orm-有对应视频教程-需要可找我领取

首先,我定义了两个自定义注解,Table和Field。

package 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 Table {
	String value(); //表名
}

先来看Table,这个注解是在运行时读取,因此其保留策略时是RetentionPolicy.RUNTIME,这个注解的主要作用是放在实体类上将实体类映射为数据库中的表名,因此,它的运行目标是ElementType.FIELD。 

package 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 Field {
	String name(); // 数据库字段名
	String type(); // 数据字段类型
	int length(); // 数据库中字段长度
}

自定义注解Field,主要用于将实体类里面的属性映射为数据库表中的字段信息。 这个注解是在运行时读取,因此其保留策略时是RetentionPolicy.RUNTIME,这个注解主要放在实体类的属性上,因此其运行目标是ElementType.FIELD。

package entity;

import annotation.Field;
import annotation.Table;

@Table("tb_commodity")
public class Commodity {
	@Field(name="id", type="integer", length=11)
	private int id;
	@Field(name = "good_name", type="varchar", length = 30)
	private String name;
	@Field(name="good_price", type="integer", length=11)
	private int price;

	public int getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getPrice() {
		return price;
	}

	public void setPrice(int price) {
		this.price = price;
	}
}

定义一个封装商品表信息的实体类Commodity,用上我们刚刚定义的两个注解。

package core;

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

import annotation.Table;

public class ProcessAnnotionDemo {
	public static void main(String[] args) throws ClassNotFoundException {
		Class clazz = Class.forName("entity.Commodity");
		
		for (Annotation annotation : clazz.getAnnotations()) {
			if (annotation instanceof Table) {
				Table t = (Table)annotation;
				System.out.println(t.value());
			}
		}
		
		for (Field field : clazz.getDeclaredFields()) {
			for (Annotation annotation : field.getAnnotations()) {
				if (annotation instanceof annotation.Field) {
					annotation.Field f = (annotation.Field)annotation;
					System.out.println(f.name() + "," + f.type() + "," + f.length());
				}
			}
		}
	}
}

通过java的反射,得到实体类 Commodity的注解信息,最终可以将该实体类映射成表名为tb_commodity,字段为good_name,good_price的数据库信息。

运行效果如下图所示

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/324600.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号