mybatis批量增加与删除——(十五)

2018-06-18 00:00:34来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

1.首先应该明白,mybatis增删改返回值是int型的影响行数的值

 

mapper接口

package cn.xm.mapper;

import java.util.List;

import cn.xm.pojo.Questions;


/**
 * 自定义的批量删除与批量增加试题
 * @author liqiang
 *
 */
public interface QuestionsCustomMapper {
    /**
     * 批量导入试题
     * @param list 需要倒入的试题集合
     * @return
     * @throws Exception
     */
    public int saveQuestionBatch()throws Exception; 

}

 

 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">

<!-- namespace命名空间,作用就是对sql进行分类化管理,理解sql隔离 注意:使用mapper代理方法开发,namespace有特殊重要的作用 -->
<mapper namespace="cn.xm.mapper.QuestionsCustomMapper">

    <insert id="saveQuestionBatch">
        INSERT INTO `exam`.`questions`
        VALUES ('7',
        '1',
        '测试题目7',
        NULL,
        NULL,
        NULL,
        NULL,
        NULL,
        NULL,
        NULL,
        NULL,
        "安全知识")
    </insert>

</mapper>

 

 

测试代码:

package cn.xm.test.mybatis;

import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.List;

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 org.apache.tomcat.jdbc.pool.interceptor.SlowQueryReportJmxMBean;
import org.junit.Before;
import org.junit.Test;

import cn.xm.mapper.EmployeeInMapper;
import cn.xm.mapper.QuestionsCustomMapper;
import cn.xm.pojo.EmployeeIn;
import cn.xm.pojo.EmployeeInExample;

public class MybatisTest2 {

    private SqlSessionFactory sqlSessionFactory;

    @Before
    public void setUp() throws Exception {
        // 将全局配置文件作为一个流
        String resource = "sqlMapConfig.xml";
        String realPath = this.getClass().getClassLoader().getResource("sqlMapConfig.xml").getPath();
        InputStream inputStream = Resources.getResourceAsStream(resource);
        // 建立一个SqlSession工厂
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    }

    // 测试增加
    @Test
    public void testAdd() throws Exception {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        QuestionsCustomMapper qsm = sqlSession.getMapper(QuestionsCustomMapper.class);
        int total = qsm.saveQuestionBatch();
        System.out.println(total);
        sqlSession.commit();
        sqlSession.close();
    }

}

 

结果:

 

2.批量增加

  sql语句:  insert into xxx values ("xx1",'xxx1'),("xx2","xxx2"),("xx3","xxx3")

 

mapper接口

/**
     * 批量导入试题
     * @param list 需要倒入的试题集合
     * @return 影响的行数
     * @throws Exception
     */
    public int saveQuestionBatch(List<Questions> list)throws Exception;

 

 

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">

<!-- namespace命名空间,作用就是对sql进行分类化管理,理解sql隔离 注意:使用mapper代理方法开发,namespace有特殊重要的作用 -->
<mapper namespace="cn.xm.mapper.QuestionsCustomMapper">

    <!-- INSERT INTO `exam`.`questions` VALUES ('7', '1', '测试题目7', NULL, NULL, 
        NULL, NULL, NULL, NULL, NULL, NULL, "安全知识") -->
    <insert id="saveQuestionBatch" parameterType="java.util.List">
        INSERT INTO `exam`.`questions`
        VALUES
        <foreach collection="list" item="question" separator=",">
            (#{question.questionid},#{question.questionbankid},#{question.question},#{question.questionwithtag},#{question.answer},#{question.analysis},#{question.type},#{question.level},#{question.employeeid},#{question.uploadtime},#{question.status},#{question.knowledgetype})
        </foreach>
    </insert>


</mapper>

 

 

测试代码:

package cn.xm.test.mybatis;

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

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 org.junit.Before;
import org.junit.Test;

import cn.xm.bean.basebean.Questions;
import cn.xm.mapper.QuestionsCustomMapper;


public class MybatisTest2 {

    private SqlSessionFactory sqlSessionFactory;

    @Before
    public void setUp() throws Exception {
        // 将全局配置文件作为一个流
        String resource = "sqlMapConfig.xml";
        String realPath = this.getClass().getClassLoader().getResource("sqlMapConfig.xml").getPath();
        InputStream inputStream = Resources.getResourceAsStream(resource);
        // 建立一个SqlSession工厂
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    }
// 测试批量增加
    @Test
    public void testBatchAdd() throws Exception {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        QuestionsCustomMapper qsm = sqlSession.getMapper(QuestionsCustomMapper.class);
        List<Questions> list = new ArrayList<>();
        list.add(new Questions("8", "1", "测试题目8", "", "", "", "", "", "",null, "", ""));
        list.add(new Questions("9", "1", "测试题目8", "", "", "", "", "", "",null, "", ""));
        list.add(new Questions("10", "1", "测试题目8", "", "", "", "", "", "",null, "", ""));
        list.add(new Questions("11", "1", "测试题目8", "", "", "", "", "", "",null, "", ""));
        int total = qsm.saveQuestionBatch(list);
        System.out.println(total);
        sqlSession.commit();
        sqlSession.close();
    }

}

   总结:传入单个List上面SQL中collection名字应该是list,输入类型是List

 

3.批量删除

 

sql语句:  DELETE FROM `exam`.`questions` WHERE `questionId` IN ('10','11','8','9')

 

java接口:

/**
     * 批量删除
     * @param ids id集合
     * @return  删除条数
     * @throws Exception
     */
    public int deleteQuestionBatch(List<String> ids)throws Exception; 

 

 

mapper.xml

<!-- 批量删除 -->
    <!-- DELETE FROM `exam`.`questions` WHERE `questionId` in ('10','11','8','9') -->
    <delete id="deleteQuestionBatch" parameterType="java.util.List">
        DELETE FROM `exam`.`questions` WHERE `questionId` in 
        <foreach collection="list" item="id" separator="," open="(" close=")">
            #{id}
        </foreach>
    </delete>

 

 

测试代码:

package cn.xm.test.mybatis;

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

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 org.junit.Before;
import org.junit.Test;

import cn.xm.bean.basebean.Questions;
import cn.xm.mapper.QuestionsCustomMapper;

public class MybatisTest2 {

    private SqlSessionFactory sqlSessionFactory;

    @Before
    public void setUp() throws Exception {
        // 将全局配置文件作为一个流
        String resource = "sqlMapConfig.xml";
        String realPath = this.getClass().getClassLoader().getResource("sqlMapConfig.xml").getPath();
        InputStream inputStream = Resources.getResourceAsStream(resource);
        // 建立一个SqlSession工厂
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    }


    // 测试批量删除
    @Test
    public void testBatchDelete() throws Exception {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        QuestionsCustomMapper qsm = sqlSession.getMapper(QuestionsCustomMapper.class);
        List<String> ids = new ArrayList<>();
        ids.add("8");
        ids.add("9");
        ids.add("10");
        ids.add("11");
        int total = qsm.deleteQuestionBatch(ids);
        System.out.println(total);
        sqlSession.commit();
        sqlSession.close();
    }

}

 

 

 

 

 

-------------------第二种方法-------------------

实体类:

复制代码
import java.io.Serializable;
public class AttachmentTable implements Serializable {
    private static final long serialVersionUID = 8325882509007088323L;
    private Integer id;
    // 附件名称
    private String name;
    // 日志ID
    private Integer logid;
    // 附件URL
    private String url;

    // getter/setter.......
}
复制代码

Mapper接口:

复制代码
import java.util.List;
import model.AttachmentTable;
public interface AttachmentTableMapper {
  int insert(AttachmentTable record);
  void insertByBatch(List<AttachmentTable> attachmentTables); }
复制代码

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="mapper.AttachmentTableMapper">
    <resultMap id="BaseResultMap" type="model.AttachmentTable">
        <id column="id" jdbcType="INTEGER" property="id" />
        <result column="name" jdbcType="VARCHAR" property="name" />
        <result column="logID" jdbcType="INTEGER" property="logid" />
    </resultMap>
    <resultMap extends="BaseResultMap" id="ResultMapWithBLOBs" type="model.AttachmentTable">
        <result column="url" jdbcType="LONGVARCHAR" property="url" />
    </resultMap>
    <sql id="Base_Column_List">
        id, name, logID
    </sql>
    <sql id="Blob_Column_List">
        url
    </sql>
    <insert id="insert" parameterType="model.AttachmentTable">
        insert into attachment_table (id, name, logID,url)
        values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{logid,jdbcType=INTEGER},#{url,jdbcType=LONGVARCHAR})
    </insert>
    <insert id="insertByBatch" parameterType="java.util.List">
        insert into attachment_table (name, logID,url)
        values
        <foreach collection="list" item="item" index="index" separator=",">
            (#{item.name,jdbcType=VARCHAR}, #{item.logid,jdbcType=INTEGER},#{item.url,jdbcType=LONGVARCHAR})
        </foreach>
    </insert>
</mapper>
复制代码

【注:标红的地方是需要注意的地方,我第一次做时直接“#{name,jdbcType=VARCHAR}”,没有加前缀“item”,导致报错“找不到name”】

 (二)多参数批量删除示例

package com.vrv.linkdood.app.workreport.demomodule.mapper;import org.apache.ibatis.annotations.Param;public interface AttachmentTableMapper {
    void deleteByLogIdAndNames(@Param("logid") Integer logID, @Param("names") String[] names);
}
复制代码
    <delete id="deleteByLogIdAndNames">
        delete from attachment_table
        where logid = #{logid,jdbcType=INTEGER} AND NAME IN
        <foreach collection="names" item="item" index="index" open="(" close=")" separator=",">
            #{item}
        </foreach>
    </delete>
复制代码

 

复制代码

属性 描述
item 循环体中的具体对象。支持属性的点路径访问,如item.age,item.info.details。
具体说明:在list和数组中是其中的对象,在map中是value。
该参数为必选。
collection

要做foreach的对象,作为入参时,List<?>对象默认用list代替作为键,数组对象有array代替作为键,Map对象没有默认的键。
当然在作为入参时可以使用@Param("keyName")来设置键,设置keyName后,list,array将会失效。 除了入参这种情况外,还有一种作为参数对象的某个字段的时候。举个例子:
如果User有属性List ids。入参是User对象,那么这个collection = "ids"
如果User有属性Ids ids;其中Ids是个对象,Ids有个属性List id;入参是User对象,那么collection = "ids.id"
上面只是举例,具体collection等于什么,就看你想对那个元素做循环。
该参数为必选。

separator 元素之间的分隔符,例如在in()的时候,separator=","会自动在元素中间用“,“隔开,避免手动输入逗号导致sql错误,如in(1,2,)这样。该参数可选。
open foreach代码的开始符号,一般是(和close=")"合用。常用在in(),values()时。该参数可选。
close foreach代码的关闭符号,一般是)和open="("合用。常用在in(),values()时。该参数可选。
index 在list和数组中,index是元素的序号,在map中,index是元素的key,该参数可选。
 
复制代码

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:【MySQL】online ddl 工具之pt-online-schema-change

下一篇:mysql批量删除相同前缀的表和修改表名