mybatis输出SQL格式化方式

作者:restService 时间:2021-06-18 18:19:45 

mybatis输出SQL格式化

通过第三方日志工具可以控制日志级别的输出,但是我们发现mybatis输出的SQL不是那么的完整,我们SQL里的参数值并没有打印出来,下面我就来讲讲怎么样对mybatis的输出sql格式化。

首先我这个案例是基于Spring boot 来开发的,所以配置和传统的xml配置有所区别,spring boot大大简化了一些配置,它把配置放到java代码,我们只需要使用注解就可替代一些以前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 只对查询和更新语句做了格式化,其它语句需要手动添加
* @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";
   }
}

配置日志级别


<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语句格式化 trim prefix suffix

标题SQL语句格式化

  • trim标记:是格式化sql的标记

  • prefix:前缀

  • suffix:后缀

  • prefixOverrides:指定去除多余的前缀内容

  • suffixOverrides:指定去除多余的后缀内容

1. select语句


<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>

执行结果为:

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

2. insert语句


<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>

执行结果为:

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

3.update语句


 <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>

执行结果为:

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

来源:https://www.cnblogs.com/zengsong-restService/p/3296371.html

标签:mybatis,输出,SQL格式化
0
投稿

猜你喜欢

  • java synchronized的用法及原理详解

    2023-07-17 04:42:54
  • Java String转换时为null的解决方法

    2022-08-25 08:16:00
  • Android ImageButton自定义按钮的按下效果的代码实现方法分享

    2021-11-20 13:52:07
  • Android获取手机通讯录、sim卡联系人及调用拨号界面方法

    2021-07-02 00:41:07
  • 深入理解java final不可变性

    2023-02-11 20:17:27
  • MyBatis Generator去掉生成的注解

    2022-08-29 22:01:03
  • Java中RedisUtils工具类的使用

    2022-05-04 21:32:32
  • 如何用IDEA调试BUG的几种方法

    2022-08-04 17:12:46
  • Java实现插入排序算法可视化的示例代码

    2021-08-06 19:35:50
  • C#装饰者模式实例分析

    2022-07-16 00:33:53
  • Java Socket编程实例(四)- NIO TCP实践

    2021-10-07 13:44:35
  • Java异常ClassCastException的解决

    2022-10-21 02:37:13
  • C# 对PDF文档加密、解密(基于Spire.Cloud.SDK for .NET)

    2021-11-23 05:37:26
  • mybatis批量添加,批量更新之前如何判断是否已经存在

    2022-01-03 20:33:38
  • SpringBoot分离打Jar包的两种配置方式

    2023-01-30 09:06:59
  • C#中线程同步对象的方法分析

    2021-06-06 05:43:46
  • 一行代码教你解决Scrollview和TextInput焦点获取问题

    2022-03-25 21:34:58
  • Mybatis一对多查询的两种姿势(值得收藏)

    2023-07-01 00:20:08
  • Android编程单选项框RadioGroup综合应用示例

    2022-01-12 19:16:29
  • C#后端接收form-data,创建实体类教程

    2023-08-23 21:07:57
  • asp之家 软件编程 m.aspxhome.com