• 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:事务级别

  • 相关阅读:
    一个禁止某个document element对象选中文本的js方法
    LNMP中nginx和php的安装流程
    nginx编译
    nginx服务器管理
    nginx+phpfpm配置文件的组织结构
    win 8 x64 english key
    WdatePicker 设置时间范围在某个时间段
    Vm workstation安装win8 的问题
    android 开发中xml的解析
    多线程下载文件
  • 原文地址:https://www.cnblogs.com/kongbursi-2292702937/p/14680604.html
Copyright © 2020-2023  润新知