Java开发经验分享之通过MyBatis编写一个批量插入,局部更新的方法。

Java开发经验分享之通过MyBatis编写一个批量插入,局部更新的方法。(本作品为原创,如有不足之处,还望大牛多给意见。如需转载,请注明出处。谢谢!)

一、有MyBatis开发经验的小伙伴都知道,在MyBatis中的在SqlSession接口中包含了所有可能执行的sql语句,我这里就不一一列举,想了解的小伙伴请参考org.apache.ibatis.session.SqlSession源码。今天我们主要实现一个 批量插入数据操作 局部更新数据操作,只更新前端传过来字段的值。

说明:

  话不多说,直接上代码。

  Dao层实现:也是通过SqlSession 来实现这一操作。

public class BaseDaoImp<T> implements IBaseDao<T> {
    protected static Log logger = LogFactory.getLog(BaseDaoImp.class);
    /**
     * 预定义的statement
     */
protected static final String INSERT_BACTH = "insertBatch";
protected static final String UPDATE_LOCAL = "updateLocal";
protected static final String ERROR_NULL_PAREM = "参数为空,请检查!";
protected static final String ERROR_INSERT = "插入数据发生异常,请重试!"; protected static final String ERROR_UPDATE = "更新数据发生异常,请重试!";
protected static final String DOT = "."; protected Class<T> entityClass = null; @Autowired protected SqlSessionTemplate sqlSession; @SuppressWarnings("unchecked") public BaseDaoImp() { entityClass = (Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0]; } protected String getPrefix() { return entityClass.getSimpleName() + DOT; } public SqlSession getSqlSession() { return sqlSession; } public void setSqlSession(SqlSessionTemplate sqlSession) { this.sqlSession = sqlSession; }

   
/* * 局部更新,只更新前端传过来字段的值 */ public int updateLocal(Map<String, Object> params) { if (null == params) { logger.error(ERROR_NULL_PAREM); throw new ServiceException(ResultCode.FAILURE_302, ERROR_NULL_PAREM); } try { return sqlSession.update(UPDATE_LOCAL, params); } catch (ServiceException e) { throw new ServiceException(ResultCode.FAILURE_302, ERROR_UPDATE); } }
/** * 批量插入 */ public int insertBatch(List<T> list) { if (null == list || list.size() == 0) { logger.error(ERROR_NULL_PAREM); throw new ServiceException(ResultCode.FAILURE_302, ERROR_NULL_PAREM); } int result = 1; SqlSession batchSqlSession = null; try { batchSqlSession = sqlSession.getSqlSessionFactory().openSession(ExecutorType.BATCH, false);// 获取批量方式的sqlsession int batchCount = 1000;// 每批commit的个数 int batchLastIndex = batchCount;// 每批最后一个的下标 for (int index = 0; index < list.size();) { if (batchLastIndex >= list.size()) { batchLastIndex = list.size(); result += batchSqlSession.insert(getPrefix() + INSERT_BACTH,list.subList(index, batchLastIndex)); batchSqlSession.commit(); System.out.println("index:" + index + " batchLastIndex:" + batchLastIndex); break;// 数据插入完毕,退出循环 } else { result += batchSqlSession.insert(getPrefix() + INSERT_BACTH,list.subList(index, batchLastIndex)); batchSqlSession.commit(); System.out.println("index:" + index + " batchLastIndex:" + batchLastIndex); index = batchLastIndex;// 设置下一批下标 batchLastIndex = index + (batchCount - 1); } } batchSqlSession.commit(); return result; } catch (ServiceException e) { throw new ServiceException(ResultCode.FAILURE_302, ERROR_INSERT); } finally { batchSqlSession.close(); } }

}

XML代码实现如下:

局部更新操作:

    <!-- 局部更新操作 -->
    <update id="updateLocal" parameterType="java.util.Map">
        UPDATE TABLE SET
        <foreach collection="params.keys" item="key" index="index"
            separator=",">
            <!-- 将对应的value赋值给对应的Key(key和数据库的字段一样) -->
            <if test="key != 'FD_ID'">
                ${key}=#{params[${key}]}
            </if>
        </foreach>
        <!--#{1}表示接受Dao层方法传入的第二个参数 -->
        where FD_ID = #{params[FD_ID]}
    </update>

批量插入数据操作:

 <!-- 批量插入数据操作 -->
<insert id="insertBatch" parameterType="java.util.List"> insert into TABLE (Field_1,
Field_2,
Field_3, Field_4 ) select t.
* from ( <foreach collection="list" item="item" index="index" separator="UNION ALL"> (SELECT #{item.field1,jdbcType=VARCHAR}, #{item.field2,jdbcType=VARCHAR}, #{item.field3,jdbcType=VARCHAR}, #{item.field4,jdbcType=VARCHAR} FROM dual) </foreach> ) t </insert>

 

转载于:https://www.cnblogs.com/JimYi/p/10330657.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值