zoukankan      html  css  js  c++  java
  • Mybatis的执行器

    1、执行器三种类型

    • ExecutorType.SIMPLE(默认执行器

      可以返回自增键,只需要在mapper文件中,增加属性: useGeneratedKeys="true" keyProperty="productId",那么自增键会在事务提交后,自动设置到传入的    user对象中

    这个类型不做特殊的事情,它只为每个语句创建一个PreparedStatement。

    • ExecutorType.REUSE

    这种类型将重复使用PreparedStatements。

    • ExecutorType.BATCH

    这个类型批量更新,且必要地区别开其中的select 语句,确保动作易于理解。

    2、以下是xml文件中配置sqlsession对象并设置执行器

    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">  
        <constructor-arg index="0" ref="fsasSqlSessionFactory" />  
        <constructor-arg index="1" value="SIMPLE" />  
    </bean>  

    也可以在SqlSessionFactory对象获取sqlsession的时候指定执行器:

    sqlSessionFactory.openSession(ExecutorType.BATCH);

    如果使用SIMPLE执行器,那么要想批量插入数据,需要在mapper.xml文件中使用foreach标签

    <!-- 批量插入user -->  
    <insert id="insertUsers" parameterType="map" useGeneratedKeys="true"  
        keyProperty="userId">  
        INSERT  
        INTO user (  
        <include refid="userColumns" />  
        , create_time,  
        update_time)  
        VALUES  
        <foreach collection="users" item="userCommand" index="index"  
            separator=",">  
            (#{userCommand.email},  
            #{userCommand.pwd},#{userCommand.nickname},  
            #{userCommand.phone},  
            #{userCommand.sign}, #{userCommand.age},  
            #{userCommand.birthday},  
            #{userCommand.sex},  
            #{userCommand.createTime},  
            now())  
        </foreach>  
    </insert>  

    使用BATCH执行器,那么要想批量插入数据只需要使用同一个sqlsession创建的对象即可

    SqlSession session = sqlSessionTemplate.getSqlSessionFactory()  
                   .openSession(ExecutorType.BATCH, false);  
           try {  
               UserDao batchUserDao = session.getMapper(UserDao.class);  
      
               for (UserCommand user : users) {  
                   batchUserDao.insertUser(user);  //只需要用这一个对象
               }  
               session.commit();  
               // 清理缓存,防止溢出  
               session.clearCache();  
      
               // 添加位置信息  
               userLbsDao.insertUserLbses(users);  
      
           } finally {  
               session.close();  
           }  

    3、SqlSessionFactory可以通过openSession获取SqlSession对象,这个方法有一些参数:

    ExecutorType execType:执行器类别(我们上面讲的那三种)

    boolean autoCommit:是否自动提交事务(插入数据或者更新数据都需要提交事务,否则数据不会更新到本地硬盘)

    TransactionIsolationLevel level:事务级别

  • 相关阅读:
    ES6入门 阮一峰
    NPM
    移动端BUG
    配置每次git push 不需要输入账号密码
    移动端rem布局,用户调整手机字体大小或浏览器字体大小后导致页面布局出错问题
    课程表
    岛屿数量
    二叉树的右视图
    c++设计模式——工厂模式
    克隆图
  • 原文地址:https://www.cnblogs.com/kongbursi-2292702937/p/14680604.html
Copyright © 2011-2022 走看看