基於JDBC寫一個和mybatis類似的對映框架—DBUtils

X.I.O發表於2020-12-12

基於JDBC的DBUtils

必須要依賴jdbc的jar包,篇幅原因
maven:

  <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.45</version>
   </dependency>

建立連線資訊物件

public class SqlData {

    private String driver="com.mysql.jdbc.Driver";

    private String url;

    private String username="root";

    private String password="root";

    private String database;

    public SqlData(String database) {
        this.database = database;
        this.url="jdbc:mysql://localhost:3306/"+database+"?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=UTC";
    }

    public SqlData(String database,String username,String password) {
        this.database = database;
        this.username=username;
        this.password=password;
        this.url="jdbc:mysql://localhost:3306/"+database+"?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=UTC";
    }



    public SqlData(String database,String password) {
        this.database = database;
        this.password=password;
        this.url="jdbc:mysql://localhost:3306/"+database+"?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=UTC";
    }



    public SqlData(String driver, String url, String username, String password, String database) {
        this.driver = driver;
        this.url = url;
        this.username = username;
        this.password = password;
        this.database = database;
    }
    //省略get和set方法
}

JDBC連線配置

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnectionConfig {

    private Connection conn = null;

    public Connection getConn(SqlData sqlData){
        String driver = sqlData.getDriver();
        String url = sqlData.getUrl();
        String username = sqlData.getUsername();
        String password = sqlData.getPassword();
        try{
            //獲取連線物件Connection
            Class.forName(driver);
            conn = DriverManager.getConnection(url,username,password);
        }catch (ClassNotFoundException e) {
            e.printStackTrace();
        }catch (SQLException e){
            e.printStackTrace();
            close();
        }
        return conn;
    }

    private void close(){
        try{
            conn.close();
        }catch (SQLException e){
            e.printStackTrace();
        }
    }
}

DBUtils工具

package com.xx.main;



import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;


public class DBUtils {
	//獲取連線通道(注意sqldata預設資訊是否正確)
	//可以定義一個全域性的Sqldata,為其新增更改形參的方法,可以隨意更換資料來源,和資料庫
    private static Connection getConbection(){
        return new ConnectionConfig().getConn(new SqlData("庫名"));
    }
	
	  //執行sql獲取訪問資訊
    private static ResultSet sqlExecute(String sql){
        Statement stmt = null;
        Connection conn = null;
        ResultSet rs=null;
        try {
            conn=getConbection();
            stmt = conn.createStatement();
            rs = stmt.executeQuery(sql);
        }catch (Exception e){
            e.printStackTrace();
        }
        return rs;
    }

	//sqlForm為表名
	//通過表名獲取表單所有資料 String 為表欄位 ,Object為欄位對應資料
	//獲取一條資料為在sql後面拼接limit 1 不用list新增,直接返回Map就行
    public static List<Map<String,Object>> getFormList(String sqlForm) throws Exception {
        String sql = "select * from" + sqlForm;
        ResultSet rs = sqlExecute(sql);
        ResultSetMetaData rsmd = rs.getMetaData();
        String[] lie = new String[rsmd.getColumnCount()];
        for (int i = 1; i < rsmd.getColumnCount() + 1; i++) {
            lie[i - 1] = rsmd.getColumnName(i);
        }
        List<Map<String, Object>> formList = new ArrayList<>();
        while (rs.next()) {
            Map<String, Object> map = new HashMap<>();
            for (int i = 0; i < lie.length; i++) {
                Object value = rs.getObject(lie[i]);
                map.put(lie[i], value);
            }
            formList.add(map);
        }
        return formList;
    }
	
	//cls為物件的反射,此方法物件名要與資料庫名儲存一致
	//注意資料庫欄位的字串與數字,定義物件儘可能保持資料一致
    public static <T> List<T> getObjectList(Class<T> cls) throws Exception{
        String sql="select ";
        cls.getSimpleName();
        Field[] fields=cls.getDeclaredFields();
        for (int i = 0; i < fields.length ; i++) {
            if (i<fields.length-1){
                sql+=fields[i].getName()+",";
            }else {
                sql+=fields[i].getName() + " from "+cls.getSimpleName();
            }
        }
        ResultSet rs=sqlExecute(sql);
        List<T> list=new ArrayList<>();
        while (rs.next()){
            T bean=cls.newInstance();
            for (int i = 0; i < fields.length ; i++) {
                fields[i].setAccessible(true);
                Object value=rs.getObject(fields[i].getName());
                fields[i].set(bean,value);
            }
            list.add(bean);
        }
        return list;
    }
}

相關文章