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:事務級別