Encapsulation of jdbc (BaseDao) tool class based on DBUtils

​​​​

  • Realize the connection of the database connection pool, and provide the encapsulation processing of simple transactions (ensure that the transaction is opened, committed or rolled back is the same object)
public class DBUtils { 
    private static DataSource dataSource; 
    private static ThreadLocal<Connection> threadLocal=new ThreadLocal<>(); 
    //initialize druid database connection pool 
    static { 
        //create input stream 
        InputStream stream = DBUtils.class.getClassLoader().getResourceAsStream ("jdbc.properties"); 
        Properties properties = new Properties(); 
        //Load the information in the configuration file into properties 
        try { 
            properties.load(stream); 
            //Method 1: Create a data source through the druid factory 
            / / Create a druid data connection pool and complete the initialization of the data pool 
            dataSource = DruidDataSourceFactory.createDataSource(properties); 
            Connection connection = dataSource.getConnection();
            threadLocal.set(connection);  
        } catch (Exception e) {
            e.printStackTrace(); 

        } 
    } 
    /** 
     * Get a normal connection 
     * @return connection 
     */ 
    public static Connection getConnection(){ 
        try { 
            return dataSource.getConnection(); 
        } catch (SQLException e) { 
            //If the connection fails, throw a runtime exception 
            throw new RuntimeException("The connection pool failed to obtain the connection!"); } } 
        / 
    ** 
    * 
     Get a connection to open a transaction 
     * @return connection 
     */ 
    public static Connection openTransaction(){ 
        Connection connection=threadLocal.get();
        try { 
        } catch (SQLException e) { 
            if (connection==null){
                connection = dataSource.getConnection(); 
                threadLocal.set(connection); 
            } 
            connection.setAutoCommit(false); 
            System.out.println("Open transaction: "+connection); 
        } catch (SQLException e) { 
            e.printStackTrace() ; 
        } 
        return connection; 
    } 
    /** 
     * Commit the transaction and close the connection 
     */ 
    public static void commit(){ 
        Connection connection=threadLocal.get(); 
        System.out.println("Commit the transaction: "+connection); 
        try { 
            connection.commit(); 
            throw new RuntimeException("Transaction commit failed!"); 
        } finally { 
           if(connection!=null){ 
               try { 
                   threadLocal.remove(); 
                   connection.close(); 
               } catch (SQLException e) { 
                   e.printStackTrace(); 
               } 
           } 
        } } 
    / 
    ** 
     * Roll back the transaction and close the connection 
     */ 
    public static void rollback() { 
        Connection connection = threadLocal.get(); 
        System.out.println("Rollback transaction: "+connection); 
        try { 
            connection. rollback(); 
        } catch (SQLException e) { 
            e.printStackTrace() ; 
            throw new RuntimeException("Database rollback failed");
        } finally {
            if(connection!=null){
                try {
                    threadLocal.remove();
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
//关闭连接
    public static void close(Connection connection){
        if (connection!=null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

  • Use DBUtils to encapsulate BaseDao
public abstract class BaseDao { 
    QueryRunner queryRunner=new QueryRunner(); 
    /** 
     * Responsible for executing delete/update/insert operations 
     * @param sql 
     * @param args 
     * @return Return -1 means the execution failed, and the row affected by the success of other generation operations Number 
     */ 
    public int update(String sql,Object...args){ 
        Connection connection = DBUtils.getConnection(); 
        try { 
            return queryRunner.update(connection,sql,args); 
        } catch (SQLException e) { 
            e.printStackTrace (); 
        } finally { 
            DBUtils.close(connection); 
        } 
        return -1; 
    } 

    /** 
     * Execute the query statement and return a javabean object
     * @param type 
     * @param sql 
     * @param args 
     * @param <T> generic, representing a specific javabean object 
     * @return 
     */ 
    public <T>T selectSingleObject(Class<T>type,String sql,Object.. .args){ 
        Connection connection = DBUtils.getConnection(); 

        try { 
            return queryRunner.query(connection,sql,new BeanHandler<T>(type),args); 
        } catch (SQLException e) { 
            e.printStackTrace(); 
        } finally { 
            DBUtils.close(connection); 
        } 
        return null; 
    } 

    /** 
     * Execute the query statement and return a list collection 
     * @param type 
     * @param sql
     * @param args
     * @param <T>
     * @return
     */
    public <T> List<T> selectManyObject(Class<T>type, String sql, Object...args){
        Connection connection = DBUtils.getConnection();
        try {
            return queryRunner.query(connection,sql,new BeanListHandler<T>(type),args);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtils.close(connection);
        }
        return null;
    }

    /**
     * 返回一行或一列
     * @param sql
     * @param args
     * @return
     */
    public Object selectObject(String sql, Object...args){
        Connection connection = DBUtils.getConnection();
        try {
            return queryRunner.query(connection,sql,new ScalarHandler(),args);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtils.close(connection);
        }
        return null;
    }
}

Guess you like

Origin blog.csdn.net/weixin_45533131/article/details/126820057