框架:Mybatis批量操作

一、批量操作

      1、添加依赖包,参考上篇文章 Mybatis+mysql入门使用

      2、初始化数据库和初始数据,以mysql为例

DROP DATABASE IF EXISTS moy_mybatis;
CREATE DATABASE moy_mybatis CHARACTER SET UTF8;
USE moy_mybatis;

DROP TABLE  IF EXISTS t_test;

CREATE TABLE t_test(
    id int(11) AUTO_INCREMENT,
    create_time DATE comment '创建时间',
    modify_time DATE comment '修改时间',
    content VARCHAR (50) comment '内容',
    PRIMARY KEY (id)
);
View Code

      3、新建实体类TestEntity

package com.moy.mybatis3.entity;

import java.util.Date;

/**
 * [Project]:moy-gradle-project  <br/>
 * [Email]:moy25@foxmail.com  <br/>
 * [Date]:2018/2/20  <br/>
 * [Description]:  <br/>
 *
 * @author YeXiangYang
 */
public class TestEntity {
    private Integer id;
    private Date createTime;
    private Date modifyTime;
    private String content;

    public Integer getId() {
        return id;
    }

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

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public Date getModifyTime() {
        return modifyTime;
    }

    public void setModifyTime(Date modifyTime) {
        this.modifyTime = modifyTime;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    @Override
    public String toString() {
        return "TestEntity{" +
                "id=" + id +
                ", createTime=" + createTime +
                ", modifyTime=" + modifyTime +
                ", content='" + content + '\'' +
                '}';
    }
}
View Code

      4、新建实体对应配置文件Test.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="com.moy.mybatis3.mapper.TestMapper">
    <delete id="deleteBatch">
        delete FROM t_test WHERE id in (
        <foreach collection="array" item="id" separator=",">
            #{id}
        </foreach>
        )
    </delete>

    <insert id="insertBatch">
        INSERT INTO t_test (create_time,modify_time,content)
        VALUES
        <foreach collection="list" item="TestEntity" separator=",">
            (#{TestEntity.createTime},#{TestEntity.modifyTime},#{TestEntity.content})
        </foreach>
    </insert>
</mapper>
View Code

      5、编写接口TestMapper

package com.moy.mybatis3.mapper;

import com.moy.mybatis3.entity.TestEntity;

import java.io.Serializable;
import java.util.List;

/**
 * [Project]:moy-gradle-project  <br/>
 * [Email]:moy25@foxmail.com  <br/>
 * [Date]:2018/2/20  <br/>
 * [Description]:  <br/>
 *
 * @author YeXiangYang
 */
public interface TestMapper {

    int insertBatch(List<TestEntity> list);

    int deleteBatch(Serializable[] id);
}
View Code

      6、为了方便测试,编写一个获取SqlSession的工具类Mybatis3Utils

package com.moy.mybatis3.utils;

import org.apache.ibatis.io.Resources;
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.Reader;
import java.util.Objects;

/**
 * [Project]:moy-gradle-project  <br/>
 * [Email]:moy25@foxmail.com  <br/>
 * [Date]:2018/2/19  <br/>
 * [Description]:  <br/>
 *
 * @author YeXiangYang
 */
public abstract class Mybatis3Utils {

    public static final SqlSessionFactory sqlSessionFactory;
    public static final ThreadLocal<SqlSession> sessionThread = new ThreadLocal<>();

    static {
        try {
            Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static SqlSession getCurrentSqlSession() {
        SqlSession sqlSession = sessionThread.get();
        if (Objects.isNull(sqlSession)) {
            sqlSession = sqlSessionFactory.openSession();
            sessionThread.set(sqlSession);
        }
        return sqlSession;
    }

    public static void closeCurrentSession() {
        SqlSession sqlSession = sessionThread.get();
        if (Objects.nonNull(sqlSession)) {
            sqlSession.close();
        }
        sessionThread.set(null);
    }
}
View Code

      7、新建mybatis配置信息文件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"/>
    </settings>

    <typeAliases>
        <package name="com.moy.mybatis3.entity"/>
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://127.0.0.1:3306/moy_mybatis?useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value="123"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="mapper/Test.xml"></mapper>
    </mappers>
</configuration>
View Code

      8、编写测试类TestMapperTest

package com.moy.mybatis3.mapper;

import com.moy.mybatis3.entity.TestEntity;
import com.moy.mybatis3.utils.Mybatis3Utils;
import org.apache.ibatis.session.SqlSession;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import static org.junit.Assert.*;

/**
 * [Project]:moy-gradle-project  <br/>
 * [Email]:moy25@foxmail.com  <br/>
 * [Date]:2018/2/20  <br/>
 * [Description]:  <br/>
 *
 * @author YeXiangYang
 */
public class TestMapperTest {

    SqlSession sqlSession;
    TestMapper testMapper;

    @Before
    public void before() {
        sqlSession = Mybatis3Utils.getCurrentSqlSession();
        testMapper = sqlSession.getMapper(TestMapper.class);
    }

    @After
    public void after() {
        Mybatis3Utils.closeCurrentSession();
    }

    @Test
    public void insertBatch() {
        int count = 10;
        List<TestEntity> list = new ArrayList<>(count);
        for (int i = 0; i < count; i++) {
            TestEntity entity = new TestEntity();
            entity.setCreateTime(new Date());
            entity.setModifyTime(new Date());
            entity.setContent("我是批量添加的内容");
            list.add(entity);
        }
        System.out.println(testMapper.insertBatch(list));
        sqlSession.commit();
    }

    @Test
    public void deleteBatch() {
        int count = 10;
        Integer[] array = new Integer[count];
        for (int i = 0; i < count; i++) {
            array[i] = i + 1;
        }
        System.out.println(testMapper.deleteBatch(array));
        sqlSession.commit();
    }
}
View Code

 

yexiangyang

moyyexy@gmail.com


 

posted @ 2018-02-21 19:24  墨阳  阅读(255)  评论(0编辑  收藏  举报