溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

mybatis輸出SQL格式化的方法是什么

發(fā)布時(shí)間:2021-11-30 16:47:39 來(lái)源:億速云 閱讀:418 作者:iii 欄目:開(kāi)發(fā)技術(shù)

這篇文章主要講解了“mybatis輸出SQL格式化的方法是什么”,文中的講解內(nèi)容簡(jiǎn)單清晰,易于學(xué)習(xí)與理解,下面請(qǐng)大家跟著小編的思路慢慢深入,一起來(lái)研究和學(xué)習(xí)“mybatis輸出SQL格式化的方法是什么”吧!

mybatis輸出SQL格式化

通過(guò)第三方日志工具可以控制日志級(jí)別的輸出,但是我們發(fā)現(xiàn)mybatis輸出的SQL不是那么的完整,我們SQL里的參數(shù)值并沒(méi)有打印出來(lái),下面我就來(lái)講講怎么樣對(duì)mybatis的輸出sql格式化。

首先我這個(gè)案例是基于Spring boot 來(lái)開(kāi)發(fā)的,所以配置和傳統(tǒng)的xml配置有所區(qū)別,spring boot大大簡(jiǎn)化了一些配置,它把配置放到j(luò)ava代碼,我們只需要使用注解就可替代一些以前xml的配置。

自定義攔截器

import java.io.PrintStream;
import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import java.util.regex.Matcher;
import org.apache.commons.collections.CollectionUtils;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.springframework.stereotype.Component;
/**
 * 自定義mybatis攔截器,格式化SQL輸出,
 *
 * @author zengsong
 * @version 1.0
 * @description 只對(duì)查詢(xún)和更新語(yǔ)句做了格式化,其它語(yǔ)句需要手動(dòng)添加
 * @date 2019/5/30 10:17
 **/
@Intercepts({@org.apache.ibatis.plugin.Signature(type=org.apache.ibatis.executor.Executor.class, method="update", args={MappedStatement.class, Object.class}), @org.apache.ibatis.plugin.Signature(type=org.apache.ibatis.executor.Executor.class, method="query", args={MappedStatement.class, Object.class, org.apache.ibatis.session.RowBounds.class, org.apache.ibatis.session.ResultHandler.class})})
@Component
public class MybatisResultInterceptor
        implements Interceptor
{
    public Object intercept(Invocation invocation)
            throws Throwable
    {
        try
        {
            MappedStatement mappedStatement = (MappedStatement)invocation.getArgs()[0];
            Object parameter = null;
            if (invocation.getArgs().length > 1) {
                parameter = invocation.getArgs()[1];
            }
            String sqlId = mappedStatement.getId();
            BoundSql boundSql = mappedStatement.getBoundSql(parameter);
            Configuration configuration = mappedStatement.getConfiguration();
            String sql = getSql(configuration, boundSql, sqlId);
            System.out.println(sql);
        }
        catch (Exception localException) {}
        return invocation.proceed();
    }
    public static String getSql(Configuration configuration, BoundSql boundSql, String sqlId)
    {
        String sql = showSql(configuration, boundSql);
        StringBuilder str = new StringBuilder(100);
        str.append(sqlId);
        str.append(":");
        str.append(sql);
        return str.toString();
    }
    private static String getParameterValue(Object obj)
    {
        String value = null;
        if ((obj instanceof String))
        {
            value = "'" + obj.toString() + "'";
        }
        else if ((obj instanceof Date))
        {
            DateFormat formatter = DateFormat.getDateTimeInstance(2, 2, Locale.CHINA);
            value = "'" + formatter.format(new Date()) + "'";
        }
        else if (obj != null)
        {
            value = obj.toString();
        }
        else
        {
            value = "";
        }
        return value;
    }
    public static String showSql(Configuration configuration, BoundSql boundSql)
    {
        Object parameterObject = boundSql.getParameterObject();
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        String sql = boundSql.getSql().replaceAll("[\\s]+", " ");
        MetaObject metaObject;
        if ((CollectionUtils.isNotEmpty(parameterMappings)) && (parameterObject != null))
        {
            TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
            if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass()))
            {
                sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(getParameterValue(parameterObject)));
            }
            else
            {
                metaObject = configuration.newMetaObject(parameterObject);
                for (ParameterMapping parameterMapping : parameterMappings)
                {
                    String propertyName = parameterMapping.getProperty();
                    if (metaObject.hasGetter(propertyName))
                    {
                        Object obj = metaObject.getValue(propertyName);
                        sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(getParameterValue(obj)));
                    }
                    else if (boundSql.hasAdditionalParameter(propertyName))
                    {
                        Object obj = boundSql.getAdditionalParameter(propertyName);
                        sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(getParameterValue(obj)));
                    }
                    else
                    {
                        sql = sql.replaceFirst("\\?", "缺失");
                    }
                }
            }
        }
        return sql;
    }
    public Object plugin(Object target)
    {
        return Plugin.wrap(target, this);
    }
    public void setProperties(Properties properties) {}
}

配置攔截器

import com.sengled.cloud.data.platform.dao.mybatis.MybatisResultInterceptor;
import java.util.Properties;
import javax.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
 * 自定義mybatis攔截器
 *
 * @author zengsong
 * @version 1.0
 * @description
 * @date 2019/5/30 10:17
 **/
@Configuration
public class MybatisInterceptorConfig
{
    @Resource
    private MybatisResultInterceptor mybatisResultInterceptor;
    @Bean
    public String myInterceptor()
    {
        Properties properties = new Properties();
        this.mybatisResultInterceptor.setProperties(properties);
        return "interceptor";
    }
}

配置日志級(jí)別

 <logger name="com.apache.ibatis" level="TRACE"/>
 <logger name="java.sql.Connection" level="DEBUG"/>
 <logger name="java.sql.Statement" level="DEBUG"/>
 <logger name="java.sql.PreparedStatement" level="DEBUG"/>
 <root level="INFO">
        <appender-ref ref="STDOUT" />
        <appender-ref ref="FILE" />
 </root>

mybatis sql語(yǔ)句格式化 trim prefix suffix

標(biāo)題SQL語(yǔ)句格式化

  • trim標(biāo)記:是格式化sql的標(biāo)記

  • prefix:前綴

  • suffix:后綴

  • prefixOverrides:指定去除多余的前綴內(nèi)容

  • suffixOverrides:指定去除多余的后綴內(nèi)容

1. select語(yǔ)句

<select id="" parameterType="" resultType="">
 select * from tb_user
 <trim perfis="WHERE" prefixOverrides = "AND | OR">
  <if test="name != null"> AND name = #{name}</if>
  <if test="gender != null"> AND gender= #{gender}</if>
 </trim>
</select>

執(zhí)行結(jié)果為:

select * from tb_user where and name = #{name} andgender = #{gender}

2. insert語(yǔ)句

<insert id="" parameterType="">
    insert into tb_user
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="id != null">
        id,
      </if>
      <if test="name!= null">
        name,
      </if>
      <if test="gender!= null">
        gender,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="id != null">
        #{id,jdbcType=BIGINT},
      </if>
      <if test="name!= null">
        #{name,jdbcType=VARCHAR},
      </if>
     <if test="gender!= null">
        #{gender,jdbcType=BIGINT},
      </if>
    </trim>
  </insert>

執(zhí)行結(jié)果為:

insert into tb_user (id,name,gender) values(1,“張三”,20)

3.update語(yǔ)句

  <update id="">
    update tb_user
     <trim prefix="set" suffix=" where id = #{id}" suffixOverrides="," >
     <if test="name != null"> name = #{name} , </if>
     <if test="gender != null"> gender = #{gender} ,</if>
    </trim>
  </update>

執(zhí)行結(jié)果為:

update tb_user set name = “張三”,gender = 30 where id = 1

感謝各位的閱讀,以上就是“mybatis輸出SQL格式化的方法是什么”的內(nèi)容了,經(jīng)過(guò)本文的學(xué)習(xí)后,相信大家對(duì)mybatis輸出SQL格式化的方法是什么這一問(wèn)題有了更深刻的體會(huì),具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是億速云,小編將為大家推送更多相關(guān)知識(shí)點(diǎn)的文章,歡迎關(guān)注!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI