MyBatis 批量插入

两种方式:

  • sqlSessionFactory.openSession(ExecutorType.BATCH)
  • 拼接批量 insert SQL 脚本

 

1、Maven 依赖

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>constxiong</groupId>
        <artifactId>demo</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <artifactId>mybatis-batchinsert</artifactId>

    <dependencies>
        <!-- MySQL 8.0.21 驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.21</version>
        </dependency>

        <!-- MyBatis -->
        <dependency>
		  <groupId>org.mybatis</groupId>
		  <artifactId>mybatis</artifactId>
		  <version>3.5.5</version>
		</dependency>

    </dependencies>

    <build>

    </build>
</project>

 

2、mybatis-config.xml 配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"></setting>
    </settings>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://172.31.32.184:3306/constxiong?serverTimezone=UTC&amp;useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="constxiong@123"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="constxiong/mapper/UserMapper.xml"/>
    </mappers>
</configuration>

 

3、Mapper 接口

package constxiong.mapper;

import constxiong.po.User;

import java.util.List;

/**
 * UserMapper 接口,映射对数据库的操作
 */
public interface UserMapper {

    List<User> selectUsers();

    int insertUser(User user);

    int deleteUsers();

    /**
     * 批量插入
     */
    int insertUserBatch(List<User> userList);
}

 

4、Mapper xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="constxiong.mapper.UserMapper">

    <select id="selectUsers" resultType="constxiong.po.User">
        select * from user
    </select>

    <insert id="insertUser" parameterType="constxiong.po.User">
        insert into user values(#{id}, #{name})
    </insert>

    <delete id="deleteUsers">
      delete from user
    </delete>

    <insert id="insertUserBatch" parameterType="java.util.List">
        insert into user values
        <foreach collection="list" item="item" separator =",">
            (#{item.id}, #{item.name})
        </foreach>
    </insert>

</mapper>

 

5、User po 模型

package constxiong.po;

/**
 * 用户表模型
 */
public class User {
    private Integer id;

    private String name;

    private String mc;

    public User(Integer id, String name) {
        this.id = id;
        this.name = name;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getMc() {
        return mc;
    }

    public void setMc(String mc) {
        this.mc = mc;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", mc='" + mc + '\'' +
                '}';
    }
}


6、测试类

package constxiong;

import constxiong.mapper.UserMapper;
import constxiong.po.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 测试 Mybatis 批量插入
 */
public class Test {

    public static void main(String[] args) throws IOException {
        testBatchInsert();
    }

    /**
     * 测试 xml 配置方式分页
     */
    private static void testBatchInsert() throws IOException {
        String resource = "mybatis-config.xml";//xml配置文件路径
        InputStream inputStream = Resources.getResourceAsStream(resource);//读取配置
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//构建 SqlSessionFactory
        SqlSession sqlSession = sqlSessionFactory.openSession(true);//通过 SqlSessionfactory 获取 SqlSession

        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);//通过 SqlSession 获取 Mapper 接口

        System.out.println("------userMapper.deleteUsers()------");
        //删除 user
        userMapper.deleteUsers();
        System.out.println();

        System.out.println("------userMapper.insertUser()------");
        //插入 user
        for (int i = 1; i <= 35; i++) {
            userMapper.insertUser(new User(i, "ConstXiong" + i));
        }
        System.out.println();

        System.out.println("------insert user batch by session------");
        insertUserBatchBySession(sqlSessionFactory);
        System.out.println();

        System.out.println("------insert user batch by sql------");
        List<User> userList = new ArrayList<>();
        for (int i = 46; i <= 55; i++) {
            userList.add(new User(i,"ConstXiong" + i));
        }
        userMapper.insertUserBatch(userList);
        System.out.println();

        System.out.println("------userMapper.selectUsers()------");
        //查询所有 user
        List<User> users = userMapper.selectUsers();
        System.out.println(users);
        System.out.println();

        //关闭 SqlSession
        sqlSession.close();
    }

    /**
     * 批量插入用户
     */
    private static void insertUserBatchBySession(SqlSessionFactory sqlSessionFactory) {
        SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        for (int i = 36; i <= 45; i++) {
            userMapper.insertUser(new User(i, "ConstXiong" + i));
        }
        sqlSession.commit();
        sqlSession.close();
    }

}

 

 


【Java学习资源】整理推荐

 

 


【Java面试题与答案】整理推荐

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值