码迷,mamicode.com
首页 > 其他好文 > 详细

Mybatis批量操作

时间:2018-02-21 19:40:09      阅读:237      评论:0      收藏:0      [点我收藏+]

标签:pack   ssl   cts   ade   参考   span   def   character   doc   

一、批量操作

      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


 

Mybatis批量操作

标签:pack   ssl   cts   ade   参考   span   def   character   doc   

原文地址:https://www.cnblogs.com/moy25/p/8457076.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!