MySQL工具类

MySQL工具类

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

//SQL配置
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface Sql {
    String URL();

    String USER_NAME();

    String PASSWORD();
}

// 排除(不查询)
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface Eliminate {
}

// 别名(当实体类属性名和对应的SQL表字段不一时使用)
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface AnotherName {
    String value();
}

public class Test {
    public static void main(String[] args) {
        MySql mySql = new MySql();
        for (User user : mySql.queryList(User.class)) {
            System.out.println(user.toString());
            System.out.println("1234567890");
        }
    }
}

// 使用注解配置工具类
@Sql(URL = "jdbc:mysql://mysql.lldwb.top:33366/workchatsql?serverTimezone=Asia/Shanghai", USER_NAME = "root", PASSWORD = "@dwb123456")
class MySql {
    //加载驱动,导入数据到数据库连接对象
    private static Connection conn;

    static {
        try {
            //加载驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (Exception e) {
            System.out.println("异常" + e.getMessage());
        }
    }

    public <T> List<T> queryList(Class<T> clazz) {
        return queryList(clazz, null);
    }

    // 传入一个实体类的类型对象返回一个实体类集合
    // wheres(条件):where 字段=?(参数)    objects:条件参数
    public <T> List<T> queryList(Class<T> clazz, String wheres, Object... objects) {
        //导入数据到数据库连接对象
        try {
            Sql sqlConnection = this.getClass().getDeclaredAnnotation(Sql.class);
            conn = DriverManager.getConnection(sqlConnection.URL(), sqlConnection.USER_NAME(), sqlConnection.PASSWORD());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        List<T> list = new ArrayList<>();
        PreparedStatement pstm;
        ResultSet rs;

        try {
            String sql = "select ";
            // 录入字段
            String fields = "";
            for (Field field : clazz.getDeclaredFields()) {
                // 排除@Eliminate的字段
                if (!field.isAnnotationPresent(Eliminate.class)) {
                    if (fields != "") {
                        fields += ",";
                    }

                    // 检测是否有别名的字段
                    if (field.isAnnotationPresent(AnotherName.class))
                        // 如果有别名录入别名
                        fields += clazz.getSimpleName() + "." + field.getDeclaredAnnotation(AnotherName.class).value();
                    else
                        fields += clazz.getSimpleName() + "." + field.getName();
                }
            }

            sql += fields + " from " + clazz.getSimpleName() + (wheres != null ? wheres : "");
            pstm = conn.prepareStatement(sql);

            for (int i=1;i<=objects.length;i++){
                pstm.setObject(i,objects);
            }

            rs = pstm.executeQuery();
            ResultSetMetaData metaData = rs.getMetaData();
            //拿到有多少列
            int count = metaData.getColumnCount();
            while (rs.next()) {
                T t = clazz.newInstance();
                for (int i = 1; i <= count; i++) {
                    for (Field field : clazz.getDeclaredFields()) {
                        String metaString = metaData.getColumnLabel(i);

                        // 检测是否有别名的字段
                        if (field.isAnnotationPresent(AnotherName.class) ? field.getDeclaredAnnotation(AnotherName.class).value().equals(metaString) : false || field.getName().equals(metaString)) {
                            // 如果有别名录入别名
                            field.setAccessible(true);
                            field.set(t, rs.getObject(i));
                        }
                    }
                }
                list.add(t);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        close(rs, pstm);
        return list;
    }

    //关闭数据库连接
    private static void close(PreparedStatement pstm) {
        try {
            if (pstm != null) {
                pstm.close();//关闭预编译对象
            }
            if (conn != null) {
                conn.close();//关闭结果集对象
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    private static void close(ResultSet rs, PreparedStatement pstm) {
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        close(pstm);
    }
}

class User {
    private int id;
    @Eliminate()
    private String name;
    @AnotherName("pwd")
    private String pwdd;
    private int unitId;
    private boolean show;
    private String remark;

    public boolean isShow() {
        return show;
    }

    public void setShow(boolean show) {
        this.show = show;
    }

    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 String getPwd() {
        return pwdd;
    }

    public void setPwd(String pwd) {
        this.pwdd = pwd;
    }

    public int getUnitId() {
        return unitId;
    }

    public void setUnitId(int unitId) {
        this.unitId = unitId;
    }

    public String getRemark() {
        return remark;
    }

    public void setRemark(String remark) {
        this.remark = remark;
    }

    @Override
    public String toString() {
        return id + ";" + name + ";" + pwdd + ";" + unitId + ";" + show + ";" + remark;
    }
}