Java面试知识点(六十五)Java注解(下)——实战篇

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_33945246/article/details/100009469

一、需求

1、用户表,字段包括:用户名,用户id,昵称,年龄,性别,所在城市,邮箱,手机号。
2、方便对每一个字段进行检索,当一个用户的信息传递进入后台(信息并不完整,可能只有一个id,或者有所在城市和邮箱号),要求根据传递的信息,查询出符合条件的所有人。
3、结果输出相应的sql语句。


二、代码实现

1、用户表user类

package test.annotation;

/**
 * @author 谢世杰
 */
@Table("user")
class User {
    @Column("id")
    private int id;
    @Column("username")
    private String username;
    @Column("nickname")
    private String nickname;
    @Column("age")
    private int age;
    @Column("city")
    private String city;
    @Column("email")
    private String email;
    @Column("phone")
    private int phone;

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

    public void setUsername(String username) {
        this.username = username;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

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

    public void setCity(String city) {
        this.city = city;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public void setPhone(int phone) {
        this.phone = phone;
    }

    public int getId() {
        return id;
    }

    public String getUsername() {
        return username;
    }

    public String getNickname() {
        return nickname;
    }

    public int getAge() {
        return age;
    }

    public String getCity() {
        return city;
    }

    public String getEmail() {
        return email;
    }

    public int getPhone() {
        return phone;
    }
}

2、注解table类

package test.annotation;

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

/**
 * @author 谢世杰
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Table {
    String value();
}

3、注解column类

package test.annotation;

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

/**
 * @author 谢世杰
 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Column {
    String value();
}

4、测试环境main类

package test.annotation;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @author 谢世杰
 */
public class Main {
    public static void main(String[] args) throws Exception {
        User user1 = new User();
        User user2 = new User();
        User user3 = new User();

        user1.setId(1995);
        user1.setNickname("xsj");
        user3.setEmail("[email protected]");

        query(user1);
        query(user2);
        query(user3);
    }

    /**
     * 根据对象的数据打印查询sql语句
     * */
    private static void query(User user) throws Exception {
        // 用于拼装sql
        StringBuilder str = new StringBuilder();
        // 获得用户类的类对象
        Class userClass = user.getClass();
        // 获得表名
        if (!userClass.isAnnotationPresent(Table.class)) {
            throw  new Exception("没有表名注解");
        }
        Table table = (Table)userClass.getAnnotation(Table.class);
        String tableName = table.value();
        // 开始拼装sql
        str.append("select * from ").append(tableName).append(" where 1=1");
        // 获得用户类中的成员变量数组
        Field[] fields = userClass.getDeclaredFields();
        // 循环得到每一个用户类成员变量和表字段名
        for (Field field : fields) {
            // 判断字段是否有注解,没有则跳过
            if (!field.isAnnotationPresent(Column.class)) {
                continue;
            }
            // 获得成员变量的注解column
            Column column = field.getAnnotation(Column.class);
            // 用户表的字段名
            String columnName = column.value();
            // 成员变量名
            String fieldName = field.getName();
            // 根据成员变量名获得get方法名
            String getMethodName = "get" + fieldName.substring(0,1).toUpperCase()
                    + fieldName.substring(1);
            // 根据方法名获得get方法
            Method method = userClass.getMethod(getMethodName);
            // 设置获得数据的变量,由于成员变量的类型不唯一,所以设置为object类型
            Object getValue = null;
            // 执行方法,获得值
            getValue = method.invoke(user);
            // 判断值是否为空,不同类型的空值不同,注意分条件判断
            if (getValue == null
                    || getValue instanceof Integer && (Integer) getValue == 0) {
                continue;
            }

            // 拼装where条件
            if (getValue instanceof Integer) {
                str.append(" and " + columnName + "="+getValue+"");
            } else {
                str.append(" and " + columnName + "='"+getValue+"'");
            }
        }
        System.out.println(str);
    }
}

执行结果:

select * from user where 1=1 and id=1995 and nickname='xsj'
select * from user where 1=1
select * from user where 1=1 and email='[email protected]'

猜你喜欢

转载自blog.csdn.net/qq_33945246/article/details/100009469