自定义注解简单使用

定义表名注解 

package com.example.demo.learn.orm;

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

/**
 * 表的别名
 * 项目中使用注解,肯定会使用反射,反射应用场景, jdbc spring ioc 常用的框架, 注解实现
 */
@Retention(RetentionPolicy.RUNTIME)
public @interface SetTable {
    String value();
}




定义描述表字段注解 

package com.example.demo.learn.orm;

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

@Retention(RetentionPolicy.RUNTIME)
public @interface SetProperty {
    String name();
    int length();
}

使用注解 

package com.example.demo.learn.orm;

/**
 * 表示用户对应的实体类
 */

@SetTable("t_tag")
public class UserEntity {

    @SetProperty(name = "user_name", length = 20)
    private String userName;
    @SetProperty(name = "age", length = 10)
    private Integer age;

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public Integer getAge() {
        return age;
    }

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

    @Override
    public String toString() {
        return "UserEntity{" +
                "userName='" + userName + '\'' +
                ", age=" + age +
                '}';
    }
}

 实现ORM框架映射,通过使用注解和反射机制

package com.example.demo.learn.orm;

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

public class Test {
    private static String path = "com.example.demo.learn.orm.UserEntity";

    public static void main(String[] args) throws ClassNotFoundException {
        Class<?> objClass = Class.forName(path);
        /**
         * 表示该类上面使用的注解,只会获取到当前类上使用的注解
         */
        Annotation[] annotations = objClass.getAnnotations();
        for (Annotation annotation : annotations) {
            System.out.println(annotation);
        }

        /**
         *获取某个注解对象,以及注解上的值
         */
        SetTable setTable = objClass.getAnnotation(SetTable.class);
        // 表的名称
        String tabName = setTable.value();

        // 所有实体类属性
        Field[] fields = objClass.getDeclaredFields();

        StringBuffer buffer = new StringBuffer();
        buffer.append("select ");
        for (int i = 0; i < fields.length; i++) {
            SetProperty property = fields[i].getAnnotation(SetProperty.class);
            String name = property.name();
            buffer.append(name);
            if (i == fields.length-1) {
                buffer.append(" from ");
            } else {
                buffer.append(" , ");
            }
        }
        buffer.append(tabName);

        System.out.println(buffer.toString());
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值