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进行批量添加

 

 

 

 

 

 

 

 

 

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