mybatis获取原生Connection及事务问题

1.获取SqlSession和关闭SqlSession
    @Resource
    protected SqlSessionTemplate sqlSessionTemplate;
/**
     * 获取原生SqlSession,需要手动关闭SqlSession
     * 对应 {@code BaseDaoImpl.closeNativeSqlSession}
     * @return
     */
    protected SqlSession getNativeSqlSession() {
        return SqlSessionUtils.getSqlSession(sqlSessionTemplate.getSqlSessionFactory(),
                sqlSessionTemplate.getExecutorType(),sqlSessionTemplate.getPersistenceExceptionTranslator());
    }
    /**
     * 关闭原生SqlSession
     * 对应 getNativeSqlSession
     * @return
     */
    protected void closeNativeSqlSession(SqlSession sqlSession){
        SqlSessionUtils.closeSqlSession(sqlSession, sqlSessionTemplate.getSqlSessionFactory());
    }

由于mybatis可以使用SqlSessionTemplate自动管理SqlSession关闭(动态代理原理)

示例:封装通用根据id删除

    @Override
    public Integer deleteById(Serializable id) {
        String logBatch = ObjectUtils.getUUID();
        if (SqlKit.isDev()) {
            c3p0log(logBatch);
        }
        StringBuffer sql = new StringBuffer();
        sql.append("delete from `").append(TABLE_NAME).append("` where `").append(TABLE_ID).append("`").append(" = ?");
        if (SqlKit.isDev()) {
            log.info("【" + logBatch + "】" + sql.toString());
            log.info("【" + logBatch + "】" + id);
        }
        SqlSession sqlSession = null;
        PreparedStatement pst = null;
        try {
            // 获取SqlSession
            sqlSession = getNativeSqlSession();
            pst = sqlSession.getConnection().prepareStatement(sql.toString());
            fillStatement(logBatch, pst, id);
            int result = pst.executeUpdate();
            log.info("【" + logBatch + "】" + "deleteById result : " + result);
            return result;
        } catch (SQLException e) {
            e.printStackTrace();
            log.error("【" + logBatch + "】" + sql.toString());
            log.error("【" + logBatch + "】" + id);
            throw new DaoException("【" + logBatch + "】" + "【deleteById error】" + e.getMessage());
        } finally {
            if (pst != null){
                close(pst);
            }
            if(sqlSession != null){
                // 关闭SqlSession
                closeNativeSqlSession(sqlSession);
            }
        }
    }

获取Connection: sqlSession.getConnection()

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值