mybatis 手动生成可执行sql

自己封装的工具类MyBatisSqlUtil

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.ParameterMode;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.TypeHandlerRegistry;


public class MyBatisSqlUtil {



    /**
     * 运行期获取MyBatis执行的SQL及参数
     * @param id             Mapper xml 文件里的select Id
     * @param parameterMap   参数
     * @param sqlSessionFactory 
     * @return
     */
    public static String getMyBatisSql(String id, Map<String,Object> parameterMap,SqlSessionFactory sqlSessionFactory) {  
        Configuration configuration = sqlSessionFactory.getConfiguration();
        MappedStatement ms = configuration.getMappedStatement(id); 
        BoundSql boundSql = ms.getBoundSql(parameterMap);  
        String sql = boundSql.getSql();
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();  
        Object parameterObject = boundSql.getParameterObject();
        TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
        if (parameterMappings != null){  
            String parameter = "null";
            String propertyName;
            MetaObject newMetaObject = configuration.newMetaObject(parameterObject);
            for (ParameterMapping parameterMapping : parameterMappings) {
                if (parameterMapping.getMode() == ParameterMode.OUT) {
                    continue;
                }
                propertyName = parameterMapping.getProperty();
                if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
                    parameter = getParameterValue(parameterObject);
                } else if (newMetaObject.hasGetter(propertyName)) {
                    parameter = getParameterValue(newMetaObject.getValue(propertyName));
                } else if (boundSql.hasAdditionalParameter(propertyName)) {
                    parameter = getParameterValue(boundSql.getAdditionalParameter(propertyName));
                }
                sql = sql.replaceFirst("\\?", parameter);
            }  
            return sql;
        }
        return null;  
    }
    /**
     * 获取参数
     *
     * @param param Object类型参数
     * @return 转换之后的参数
     */
    private static String getParameterValue(Object param) {
        if (param == null) {
            return "null";
        }
        if (param instanceof Number) {
            return param.toString();
        }
        String value = null;
        if (param instanceof String) {
            value = "'"+param.toString()+"'";;
        } else if (param instanceof Date) {
            value = "'"+DateUtil.dateToString_yyyy_MM_dd__HH_mm_ss((Date)param) +"'";;;
        } else if (param instanceof Enum) {
            value = "'"+((Enum<?>) param).name()+"'";;
        } else {
            value = param.toString();
        }
        return value;
    }
}

使用方法:

import com.zaxxer.hikari.HikariDataSource;

import org.apache.ibatis.session.SqlSessionFactory;

import org.mybatis.spring.SqlSessionFactoryBean;

import org.springframework.core.io.Resource;

import org.springframework.core.io.support.PathMatchingResourcePatternResolver;




public static void main(String[] args) throws Exception { SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); DataSource dataSource = new HikariDataSource(); sqlSessionFactoryBean.setDataSource(dataSource); PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); Resource[] resources = resolver.getResources("classpath*:mapper/*Mapper.xml"); sqlSessionFactoryBean.setMapperLocations(resources); sqlSessionFactoryBean.setTypeHandlersPackage("com.xxxx.*.model"); org.apache.ibatis.session.Configuration config = new org.apache.ibatis.session.Configuration(); config.setMapUnderscoreToCamelCase(true); sqlSessionFactoryBean.setConfiguration(config); SqlSessionFactory sessionFactory = sqlSessionFactoryBean.getObject(); Map<String,Object> parameterMap = new HashMap<>(); parameterMap.put("id", 1); String myBatisSql = MyBatisSqlUtil.getMyBatisSql("com.xxx.UserMapper.selectUserResponseById", parameterMap, sessionFactory); System.out.println(myBatisSql); }

 

关键jar引用,需注意boot项目需要在启动类添加 @SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.6</version>
        </dependency>
        

        <dependency>
            <groupId>com.zaxxer</groupId>
            <artifactId>HikariCP</artifactId>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.1</version>
        </dependency>


        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
        </dependency>

 

posted @ 2020-11-18 10:33  Binz  阅读(1624)  评论(0编辑  收藏  举报