spring手动获取Connection及事务管理

1.Spring配置事务工厂


    
    

    
        
        
        
        
    

代码中获取事务和Connection

    @Resource
    protected TransactionFactory transactionFactory;

    @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);
        }
        Transaction transaction = null;
        PreparedStatement pst = null;
        try {
            transaction = transactionFactory.newTransaction(dataSource, null, false);
            pst = transaction.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);
            try {
                transaction.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            throw new DaoException("【" + logBatch + "】" + "【deleteById error】" + e.getMessage());
        } finally {
            if (pst != null){
                close(pst);
            }
            if(transaction != null){
                try {
                    transaction.commit();
                    transaction.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

1.获取事务

transaction = transactionFactory.newTransaction(dataSource, null, false);

2.获取连接

transaction.getConnection()

3.关闭事务

if(transaction != null){
    try {
        transaction.commit();
        transaction.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

你可能感兴趣的:(spring)