Dev's

[Dev's] DB쿼리 java로 가져오기

rookas89 2023. 6. 8. 15:36
728x90

서버에서 어떤 쿼리가 동작했는지 확인하기 위해 Log4J와 같은 라이브러리를 사용한다.

Console에서 어떤 쿼리가 돌았는지 확인 가능하고, txt파일로 Log파일을 저장할수도 있다.

 

이번에 DB에서 어떤 쿼리가 어떤 파라메터로 동작했는지 DB에서 관리하는 기능을 구현하게 됬다.

쿼리가 동작 할 때, 어떤 쿼리문이 동작했는지 문자열로 받아오는 함수가 필요했다.

private String getSql(String id, Map<?, ?> param) throws Exception{
    String sql = sqlSession.getConfiguration().getMappedStatement(id).getBoundSql(param).getSql();
    List<ParameterMapping> paramMap = sqlSession.getConfiguration().getMappedStatement(id)
                                                .getBoundSql(param).getParameterMappings();
    for (ParameterMapping par : paramMap) {
        String parameter = null;
        parameter = param.get(par.getProperty()).toString();
        if(parameter != null) {
            sql = sql.replaceFirst("\\?", "'" + parameter + "'");
        } else {
            sql = sql.replaceFirst("\\?", "NULL");
        }
    }
    return sql;
}

id값은 "네임스페이스.쿼리ID"값이 들어오고

param은 VO값이 들어온다.

 

 

VO를 Map로 변환하기 위해 아래 함수도 같이 사용했다.

private Map<String, Object> convertVoToMap(Object vo) throws Exception {
    // TODO Auto-generated method stub
    Map<String, Object> result = new HashMap<String, Object>();
    BeanInfo info = Introspector.getBeanInfo(vo.getClass());
    for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
        Method reader = pd.getReadMethod();
        if (reader != null) {
            result.put(pd.getName(), reader.invoke(vo));
        }
    }
    return result;
}

나머지는 SQL문자열을 가지고 DB에 저장하면 된다.

728x90