Mybatis進階--批量新增數據

一、傳統JDBC進行批處理操作

package jdbc;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class jdbcUtil {
    private static class JdbcUtil {
    }

    //處理數據庫事務,提交事務
    public static void commit(Connection conn) {
        if (null != conn) {
            try {
                conn.commit();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    //事務的回滾
    public static void rollback(Connection conn) {
        if (null != conn) {
            try {
                conn.rollback();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    //事務的開始
    public static void begin(Connection conn) {
        if (null != conn) {
            try {
                conn.setAutoCommit(false);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }


    /**
     * 獲取數據庫的連接
     */
    public static Connection getConnection() throws Exception {
        Properties properties = new Properties();
        //速度快的方式
        //new fileinputStream()
        InputStream is = JdbcUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
        //jdbc文件 內容 以流的方式加載到properties文件中
        properties.load(is);
        String driver = properties.getProperty("driver");
        String username = properties.getProperty("username");
        String password = properties.getProperty("password");
        String url = properties.getProperty("url");
        Class.forName(driver);

        return DriverManager.getConnection(url, username, password);
    }

    public static void closeResources(Connection conn, Statement statement, ResultSet resultSet){
        if (null!=resultSet){
            try {
                resultSet.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (null!=statement){
            try {
                statement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(null!=conn){
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }


    }
}

方法二:

傳統利用for循環進行插入,存在嚴重效率問題,需要頻繁獲取Session,獲取連接

使用批處理,代碼和SQL的耦合,代碼量較大

Mybatis批量插入

  1. 藉助foreach標籤使用 insert into table values()
  2. 藉助MySQL數據庫連接屬性allowMultiQueries=true

方法二

直接把insert into移到裏邊

基於SqlSession的ExecutorType進行批量添加

 

 

 

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章