JdbcTemplate 작업 SQLServer 저장 프로세스

14042 단어
최근에 저장 프로세스를 자주 사용해야 하는데, Jdbc와 JdbcTemplate의 원본 호출은 정말 번거롭기 때문에, 나는 짬을 내서 일반적인 도구 종류를 봉하여 결과 집합과 출력 파라미터를 얻을 수 있다.코드는 다음과 같습니다.
저장 프로세스 조작 템플릿 클래스
package zze.workinglog.utils;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.CallableStatementCallback;
import org.springframework.jdbc.core.JdbcTemplate;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.*;

public class ProcTemplate {
    private JdbcTemplate jdbcTemplate;

    public ProcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    /**
     *       
     * @param procName       
     * @param outArgInfo          
     * @param inArgInfoArr         
     * @return        List   
     */
    public List exec(String procName, Map outArgInfo, Object... inArgInfoArr) {
        //            
        if (!isEven(inArgInfoArr.length)) {
            throw new RuntimeException("           ");
        }
        if (outArgInfo != null) {
            //             SQLType
            Collection values = outArgInfo.values();
            values.forEach(p -> {
                if (!(p instanceof Integer) || !(isInclude(Integer.parseInt(p.toString())))) {
                    throw new RuntimeException("       【java.sql.Types】     ");
                }
            });
        }
        //       
        Map inArgInfo = new HashMap<>();
        String inArgName = "";
        for (int i = 0; i < inArgInfoArr.length; i++) {
            boolean isArgInfo = isEven(i);
            if (isArgInfo) { //         
                inArgName = inArgInfoArr[i].toString();
            } else {//        
                inArgInfo.put(inArgName, inArgInfoArr[i]);
            }
        }
        //              
        String procPlaceHolder = genProcPlaceHolder(inArgInfo.size() + (outArgInfo != null ? outArgInfo.size() : 0));
        //      SQL
        String execSql = String.format("exec %s %s", procName, procPlaceHolder);

        return jdbcTemplate.execute(execSql,
                new CallableStatementCallback>>() {
                    @Override
                    public List> doInCallableStatement(
                            CallableStatement cs) throws SQLException,
                            DataAccessException {
                        //        
                        for (String inArgName : inArgInfo.keySet()) {
                            cs.setObject(inArgName, inArgInfo.get(inArgName));
                        }
                        if (outArgInfo != null) {
                            //       
                            for (String outArgName : outArgInfo.keySet()) {
                                cs.registerOutParameter(outArgName, (Integer) outArgInfo.get(outArgName));
                            }
                        }
                        //
                        ResultSet rs = cs.executeQuery();
                        List list = convertResultSetToList(rs);
                        if (outArgInfo != null) {
                            //        
                            for (String outArgName : outArgInfo.keySet()) {
                                outArgInfo.replace(outArgName, cs.getObject(outArgName));
                            }
                        }
                        return list;
                    }
                });
    }

    public List convertResultSetToList(ResultSet rs) throws SQLException {
        //     List
        List> resultList = new ArrayList<>();
        ResultSetMetaData metaData = rs.getMetaData();
        int columnCount = metaData.getColumnCount();
        while (rs.next()) {//          Map 
            Map rowMap = new HashMap();
            for (int i = 1; i <= columnCount; i++) {
                String columnName = metaData.getColumnName(i);
                rowMap.put(columnName, rs.getString(columnName));
            }
            resultList.add(rowMap);
        }
        rs.close();
        return resultList;
    }


    /**
     *           
     *
     * @param num        
     * @return       true,    false
     */
    private boolean isEven(int num) {
        return num % 2 == 0;
    }

    /**
     *               
     *
     * @param argCount     
     * @return       ,  ?,?,?,...
     */
    private String genProcPlaceHolder(int argCount) {
        List placeHolderList = new ArrayList<>();
        for (int i = 0; i < argCount; i++) {
            placeHolderList.add("?");
        }
        return String.join(",", placeHolderList);
    }

    /**
     *             
     *
     * @param key     
     * @return         true,     false
     * @throws IllegalAccessException
     */
    private static boolean isInclude(int key) {
        List typeCodeList = new ArrayList();
        Field[] declaredFields = Types.class.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            try {
                typeCodeList.add(declaredField.getInt(Types.class));
            } catch (IllegalAccessException e) {
                throw new RuntimeException("      ");
            }
        }
        return typeCodeList.contains(key);
    }
}

사용
//               Map ,      Map,              null
Map outArgInfo = new HashMap<>();
//       Map          ,key              ,   java.sql.Types       
outArgInfo.put("remark", Types.VARCHAR);
//       ,            List,           outArgInfo
//      param1:      
//      param2:     Map   
//      param3-n:       ,  "id",1,"name","zhang",...
List list = procTemplate.exec("proc_testOutputParam", outArgInfo, "intUserID", 22340);
//          outArgInfo    
System.out.println(outArgInfo.get("remark"));

전재 대상:https://www.cnblogs.com/zze46/p/10844624.html

좋은 웹페이지 즐겨찾기