1. 程式人生 > >使用自定義註解和反射 ,自動生成查詢語句

使用自定義註解和反射 ,自動生成查詢語句

runt entity forname == rop ava stat pri string

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.打印

技術分享圖片

使用自定義註解和反射 ,自動生成查詢語句