使用自定义注解和反射 ,自动生成查询语句

时间:2022-07-01 13:19:49

1.自定义表名注解

package com.lf.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
//自定义表名注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface SetTable {
    
    String value();

}

2.自定义属性注解

package com.lf.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
//自定义属性注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SetProperty {
    String name();
    
    int length();
}

3.用户实体

package com.lf.entity;

import com.lf.annotation.SetProperty;
import com.lf.annotation.SetTable;

@SetTable("t_user")
public class UserEntity {
    @SetProperty(length = 30, name = "user_name")
    private String userName;
    @SetProperty(length = 3, name = "user_age")
    private int userAge;
    
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public int getUserAge() {
        return userAge;
    }
    public void setUserAge(int userAge) {
        this.userAge = userAge;
    }
    
    
}

4.测试类

package com.lf.test;

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

import com.lf.annotation.SetProperty;
import com.lf.annotation.SetTable;

public class UserAnnotation {
    
    public static void main(String[] args) throws ClassNotFoundException {
        //反射获取用户实体类
        Class<?> forName = Class.forName("com.lf.entity.UserEntity");

        StringBuffer sb = new StringBuffer("select ");
        //获取用户实体类所有字段
        Field[] declaredFields = forName.getDeclaredFields();
        for (int i = 0; i < declaredFields.length; i++) {
            //获取字段上的属性注解,并得到注解的值
            SetProperty annotation = declaredFields[i].getAnnotation(SetProperty.class);
            sb.append(annotation.name());
            if(i==(declaredFields.length-1)){
                sb.append(" from ");
            }else{
                sb.append(" , ");
            }
        }
        //获取用户实体类的表名注解和注解的值
        SetTable setTable = forName.getAnnotation(SetTable.class);
        sb.append(setTable.value());
        System.out.println(sb.toString());
    }
    
}

5.打印

使用自定义注解和反射 ,自动生成查询语句