概述

批量操作普通的可以使用foreach标签拼一下sql就行了,但是量多的,拼sql就不太合适了;
其实jdbc驱动上有一个rewriteBatchedStatements=true参数可以将逐条insert into改写成为insert into values;但是有限制条件,即插入的sql字段数量都是一样的;

默认的saveBatch在有些字段为null时,insert时就忽略了这个字段,这样就造成了同一批保存的数据中,有的指定了3个字段,有的只有2个字段,导致没有优化为insert into values

foreach拼sql

使用这种方式需要在jdbc驱动链接里加上&allowMultiQueries=true参数,可以在sql语句后携带分号,实现多语句执行。同时可以执行批处理,同时发出多个SQL语句。

Integer updateShopNames(@Param("shopMemberIntentions") List<ShopMemberIntention> shopMemberIntentions);
<update id="updateShopNames" parameterType="java.util.List">
    <foreach collection="shopMemberIntentions" separator=";" item="item">
        update shop_member_intention set shop_name = #{item.shopName},shop_simple_name = #{item.shopSimpleName}, gmt_modified = gmt_modified where id = #{item.id}
    </foreach>
</update>

sqlSessionFactory批量提交

要注意在jdbc url上加上参数开启批支持

rewriteBatchedStatements=true
@Autowired
private SqlSessionFactory sqlSessionFactory;
try (SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);){
    ShopMemberIntentionMapper mapper = sqlSession.getMapper(ShopMemberIntentionMapper.class);
    for (int i = 0; i < shopMemberIntentions.size(); i++) {
        mapper.updateShopName(shopMemberIntentions.get(i));
        if(i % 200 == 0){
            sqlSession.flushStatements();
        }
    }

    sqlSession.flushStatements();
    sqlSession.commit();
}catch (Exception e) {
    log.error("supplementShopName() called with parameters => , exception = 【{}】", e.getMessage());
    sqlSession.rollback();
}finally {
    sqlSession.close();
}

如果方法上用了@Transactional注解,由于在 Spring 集成的情况下,事务连接由 Spring 管理(SpringManagedTransaction),所以这里不需要手动关闭 sqlSession,在这里手动提交(commit)或者回滚(rollback)也是无效的。如果没有使用事务注解,那就一步一步来,提交了再关闭。

批量提交只能应用于 insert, update, delete。
并且在批量提交使用时,如果在操作同一SQL时中间插入了其他数据库操作,就会让批量提交方式变成普通的执行方式,所以在使用批量提交时,要控制好 SQL 执行顺序。

纯sql

其实就是执行 insert into values sql;这种插入方式是最快的
这种方式需要注意sql语句的大小。
mysql默认接受sql的大小是1048576(1M),即数据量超过1M会报异常
(可调整my.ini文件中[mysqld]下的max_allowed_packet = 1M

一对多

detailNames为当前OrderMaster的属性名,column则是当前OrderMaster与集合元素中的关联字段,当成参数传入getDetailName
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

或者直接使用结果集嵌套
直接嵌套类似,获取的是2张表join之后的总数据。
resultMap外层按照id标签中的column分组,分完组后,
内层按照sql中的字段映射赋值,
如果有id标签那么(id相同只保留第一条)

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapper        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"        "http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.msdn.dao.TeacherMapper">    

<select id="getTeacherById" resultMap="TeacherStudent">        
select s.id sid,s.name sname,t.id tid,t.name tname        
from mybatis.student s,mybatis.teacher t        
where s.tid = t.id and t.id =#{id}    
</select>    

<resultMap id="TeacherStudent" type="Teacher">        
  <id property="id" column="tid" />        
  <result property="name" column="tname" />        
  <collection property="students" ofType="Student" >            
    <id property="id" column="sid" />            
    <result property="name" column="sname" />            
    <result property="tid" column="tid" />        
  </collection>    
</resultMap>
</mapper>

查询多对一

表结构就是上面多对一中的order_masterorder_detail,通过order_id关联
在这里插入图片描述

如果关联处需要多个字段关联如下demo

<resultMap id="StudentTeacher" type="Student">    
   <!--association关联属性  property属性名 javaType属性类型 column在多的一方的表中的列名-->    
   <association property="teacher"  column="{id=tid,name=tid}" javaType="Teacher" select="getTeacher"/>
</resultMap>
<!--这里传递过来的id,只有一个属性的时候,下面可以写任何值association中column多参数配置:    
column="{key=value,key=value}"    
其实就是键值对的形式,key是传给下个sql的取值名称,value是片段一中sql查询的字段名。-->

<select id="getTeacher" resultType="teacher">    
   select * from teacher where id = #{id} and name = #{name}
</select>

在这里插入图片描述

在这里插入图片描述
或者直接使用嵌套也行

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapper        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"        "http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.msdn.dao.StudentMapper">    

<select id="getStudent2" resultMap="studentMap">        
select s.id sid,s.name sname,t.id ttid,t.name tname        
from student s,teacher t        
where s.tid=t.id;    
</select>    

<resultMap id="studentMap" type="student">        
<id property="id" column="sid" />        
<result property="name" column="sname" />        
<!--关联对象property 关联对象在Student实体类中的属性-->        
<association property="teacher" javaType="Teacher" >            
<id property="id" column="ttid" />            
<result property="name" column="tname" />        
</association>    </resultMap></mapper>
Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐