获取MyBatis执行SQL

工具类实现代码片段

    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    public String showSql(Class<?> cls,String methodName,Object param) {
        String absoluteMetgodName=getAbsoluteMetgodName(cls,methodName);
        MappedStatement mappedStatement=sqlSessionFactory.getConfiguration().getMappedStatement(absoluteMetgodName);
        Configuration configuration=mappedStatement.getConfiguration();
        BoundSql boundSql=mappedStatement.getBoundSql(param);
        Object parameterObject = boundSql.getParameterObject();
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        String sql = boundSql.getSql().replaceAll("[\\s]+", " ");
        //CollectionUtils如无对应pom引用可换其他方法,仅判空用
        if (CollectionUtils.isNotEmpty(parameterMappings)&& Objects.nonNull(parameterObject)) {
            TypeHandlerRegistry typeHandlerRegistry=configuration.getTypeHandlerRegistry();
            MetaObject metaObject=configuration.newMetaObject(parameterObject);

            //object取值判断逻辑参考mybatis源码ParameterHandler.setParameters()
            Object[] values=parameterMappings.stream().map(it->{
                String property=it.getProperty();
                Object result;
                if (boundSql.hasAdditionalParameter(property)){
                    result=boundSql.getAdditionalParameter(property);
                }else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())){
                    result=parameterObject;
                }else{
                    result=metaObject.getValue(property);
                }
                //Object转String并拼接进Sql的逻辑可根据自己业务修改或补充
                return getParameterValue(result);
            }).toArray();
            sql=String.format(sql.replace("?","%s"),values);
        }
        return sql;
    }

    private String getAbsoluteMetgodName(Class<?> cls,String mothodName){
        return cls.getCanonicalName()+"."+mothodName;
    }

    private String getParameterValue(Object obj) {
        String value = null;
        if (obj instanceof String) {
            value = "'" + obj.toString() + "'";
        } else if (obj instanceof Date) {
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            value="to_date('"+sdf.format(obj)+"','yyyy-mm-dd hh24:mi:ss')";
        } else {
            if (obj != null) {
                value = obj.toString();
            } else {
                value = "\'\'";
            }

        }
        return value;
    }

调用代码片段
xxx.class为对应mapper的文件名

        String name="1";
        System.out.println(showSql(xxx.class,"search",name));

发表评论

电子邮件地址不会被公开。 必填项已用*标注