Hibernate是可以配置 show_sql 显示 自动生成的SQL 语句,用 format_sql 可以格式化SQL 语句,但如果用 mybatis 怎么实现这个功能呢?如果你搜索看一下,基本都是通过配置日志来实现的,比如配置我们最常用的 log4j.properties 来实现。

首页我们创建一个 java 工程叫作:mybatis12,内容与之前 Mybatis+Spring 差不多,实现一个通过指定用户ID并读取其订单列表,来观察SQL的执行情况。其工程目录结构如下:

log4j.properties 内容如下:

# by yiibai.com
log4j.rootLogger=debug,stdout,logfile
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
#log4j.appender.stdout.Target=System.err
log4j.appender.stdout.layout=org.apache.log4j.SimpleLayout
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=C:/mybatis_show_sql.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %F %p %m%n log4j.logger.com.ibatis=DEBUG
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=DEBUG
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=DEBUG
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

主类测试代码如下:

import java.io.Reader;
import java.text.MessageFormat;
import java.util.List; import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder; import com.yiibai.dao.IUser;
import com.yiibai.pojo.User; public class Main {
private static SqlSessionFactory sqlSessionFactory;
private static Reader reader; static {
try {
reader = Resources.getResourceAsReader("config/Configure.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (Exception e) {
e.printStackTrace();
}
} public static SqlSessionFactory getSession() {
return sqlSessionFactory;
} /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
SqlSession session = sqlSessionFactory.openSession();
try {
//User user = (User) session.selectOne(
// "com.yiibai.mybatis.models.UserMapper.getUserByID", 1);
IUser iuser = session.getMapper(IUser.class);
getUserList();
//testInsert();
testUpdate();
//testDelete(); } finally {
session.close();
}
}
//
public static void testInsert()
{
try
{
SqlSession session = sqlSessionFactory.openSession();
IUser userMapper = session.getMapper(IUser.class);
System.out.println("Test insert start...");
User user = new User();
user.setId(0);
user.setName("Google");
user.setDept("Tech");
user.setWebsite("http://www.google.com");
user.setPhone("120");
userMapper.insertUser(user);
session.commit(); System.out.println("\r\nAfter insert");
getUserList();
System.out.println("Test insert finished...");
}
catch (Exception e)
{
e.printStackTrace();
}
} // 用户列表
public static void getUserList(){
try
{
SqlSession session = sqlSessionFactory.openSession();
IUser iuser = session.getMapper(IUser.class);
System.out.println("Test Get start...");
printUsers(iuser.getUserList());
System.out.println("Test Get finished...");
}catch (Exception e)
{
e.printStackTrace();
}
}
public static void testUpdate()
{
try
{
SqlSession session = sqlSessionFactory.openSession();
IUser iuser = session.getMapper(IUser.class);
System.out.println("Test update start...");
printUsers(iuser.getUserList());
User user = iuser.getUser(1);
user.setName("New name");
iuser.updateUser(user);
session.commit();
System.out.println("\r\nAfter update");
printUsers(iuser.getUserList());
System.out.println("Test update finished...");
}catch (Exception e)
{
e.printStackTrace();
}
} public static void testDelete()
{
try
{
SqlSession session = sqlSessionFactory.openSession();
IUser iuser = session.getMapper(IUser.class);
System.out.println("Test delete start...");
System.out.println("Before delete");
printUsers(iuser.getUserList());
iuser.deleteUser(3);
session.commit();
System.out.println("\r\nAfter delete");
printUsers(iuser.getUserList());
System.out.println("Test delete finished...");
}catch (Exception e)
{
e.printStackTrace();
}
}
/**
*
*
* @param users
*/
private static void printUsers(final List<User> users)
{
int count = 0; for (User user : users)
{
System.out.println(MessageFormat.format("============= User[{0}]=================", ++count));
System.out.println("User Id: " + user.getId());
System.out.println("User Name: " + user.getName());
System.out.println("User Dept: " + user.getDept());
System.out.println("User Website: " + user.getWebsite());
}
}
}

执行后,在MyEclise终端输出结果如下:

DEBUG - Logging initialized using 'class org.apache.ibatis.logging.commons.JakartaCommonsLoggingImpl' adapter.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
Test Get start...
DEBUG - Opening JDBC Connection
DEBUG - Created connection 22927632.
DEBUG - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@15dd910]
DEBUG - ooo Using Connection [com.mysql.jdbc.JDBC4Connection@15dd910]
DEBUG - ==> Preparing: select * from user
DEBUG - ==> Parameters:
DEBUG - <== Total: 2
============= User[1]=================
User Id: 1
User Name: New name
User Dept: Tech
User Website: http://www.yiibai.com
============= User[2]=================
User Id: 2
User Name: Hevi
User Dept: Tech
User Website: http://www.baidu.com
Test Get finished...
Test update start...
DEBUG - Opening JDBC Connection
DEBUG - Created connection 33189144.
DEBUG - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@1fa6d18]
DEBUG - ooo Using Connection [com.mysql.jdbc.JDBC4Connection@1fa6d18]
DEBUG - ==> Preparing: select * from user
DEBUG - ==> Parameters:
DEBUG - <== Total: 2
============= User[1]=================
User Id: 1
User Name: New name
User Dept: Tech
User Website: http://www.yiibai.com
============= User[2]=================
User Id: 2
User Name: Hevi
User Dept: Tech
User Website: http://www.baidu.com
DEBUG - ooo Using Connection [com.mysql.jdbc.JDBC4Connection@1fa6d18]
DEBUG - ==> Preparing: select * from user where id=?
DEBUG - ==> Parameters: 1(Integer)
DEBUG - <== Total: 1
DEBUG - ooo Using Connection [com.mysql.jdbc.JDBC4Connection@1fa6d18]
DEBUG - ==> Preparing: UPDATE user SET name = ?, dept = ?, website = ?, phone = ? where id = ?
DEBUG - ==> Parameters: New name(String), Tech(String), http://www.yiibai.com(String), 13800009988(String), 1(Integer)
DEBUG - <== Updates: 1
DEBUG - Committing JDBC Connection [com.mysql.jdbc.JDBC4Connection@1fa6d18] After update
DEBUG - ooo Using Connection [com.mysql.jdbc.JDBC4Connection@1fa6d18]
DEBUG - ==> Preparing: select * from user
DEBUG - ==> Parameters:
DEBUG - <== Total: 2
============= User[1]=================
User Id: 1
User Name: New name
User Dept: Tech
User Website: http://www.yiibai.com
============= User[2]=================
User Id: 2
User Name: Hevi
User Dept: Tech
User Website: http://www.baidu.com
Test update finished...

MyBatis打印输出SQL语句的更多相关文章

  1. mybatis实战教程(mybatis in action)之八:mybatis 动态sql语句

    mybatis 的动态sql语句是基于OGNL表达式的.可以方便的在 sql 语句中实现某些逻辑. 总体说来mybatis 动态SQL 语句主要有以下几类:1. if 语句 (简单的条件判断)2. c ...

  2. 通过Log4j的DEBUG级别来显示mybatis的sql语句

        为了更加方便调试sql语句,需要显示mybatis的sql语句.     网络上的一般方式都是通过log4j来实现,但是很多都有问题.      经过实验,以下代码能够保持正常:(只显示myb ...

  3. springmvc 项目完整示例04 整合mybatis mybatis所需要的jar包 mybatis配置文件 sql语句 mybatis应用

    百度百科: MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBat ...

  4. Mybatis 动态Sql语句《常用》

    MyBatis 的强大特性之一便是它的动态 SQL.如果你有使用 JDBC 或其他类似框架的经验,你就能体会到根据不同条件拼接 SQL 语句有多么痛苦.拼接的时候要确保不能忘了必要的空格,还要注意省掉 ...

  5. mybatis 动态sql语句(3)

    mybatis 的动态sql语句是基于OGNL表达式的.可以方便的在 sql 语句中实现某些逻辑. 总体说来mybatis 动态SQL 语句主要有以下几类: 1. if 语句 (简单的条件判断) 2. ...

  6. mybatis 动态sql语句(1)

    mybatis 的动态sql语句是基于OGNL表达式的.可以方便的在 sql 语句中实现某些逻辑. 总体说来mybatis 动态SQL 语句主要有以下几类: 1. if 语句 (简单的条件判断) 2. ...

  7. 【spring boot】【mybatis】spring boot中mybatis打印sql语句

    spring boot中mybatis打印sql语句,怎么打印出来?[参考:https://www.cnblogs.com/sxdcgaq8080/p/9100178.html] 在applicati ...

  8. Java-MyBatis:MyBatis 3 | SQL 语句构建器类

    ylbtech-Java-MyBatis:MyBatis 3 | SQL 语句构建器类 1.返回顶部 1. SQL语句构建器类 问题 Java程序员面对的最痛苦的事情之一就是在Java代码中嵌入SQL ...

  9. mybatis 打印sql 语句

    拦截器 package com.cares.asis.mybatis.interceptor; import java.text.DateFormat; import java.util.Date; ...

随机推荐

  1. oracle 负载均衡连接方式常用SQL语句备忘录

    1.---表中有重复记录用SQL语句查询出来 select * from Recharge where RechargeSerial in (select RechargeSerial from Re ...

  2. VS2015终极卸载方法

    今天打开VS2015发现出问题了,总是停止响应,去控制面板里卸载结果像下面这样,卸载出错!于是我有开始折腾了,重新安装一遍然后,还是有问题,在卸载还是出错于是我决定通过安装介质卸载,结果,悲剧的是,启 ...

  3. Android 编程下 TextView 添加链接的一种方式

    通过如下这种方式给 TextView 添加的链接支持链接样式.点击事件.href 样式,代码如下: package cn.sunzn.tlink; import android.app.Activit ...

  4. 【Fiddler】Fiddler抓包

    简述 在调试H5页面.APP的网络请求时,常用Fiddler进行抓包,查看网络报文是否如我们设想.当然,Fiddler也可对我们电脑端发出HTTP请求进行抓包. Fiddler是以代理的形式运行的,即 ...

  5. 安装Python2.7出现configure: error: no acceptable C compiler found in $PATH错误

    安装Python2.7出现configure: error: no acceptable C compiler found in $PATH错误 安装步骤: 安装依赖 yum groupinstall ...

  6. Testng生成的测试报告乱码解决办法

    Testng生成的测试报告乱码解决办法 2017-06-16 1 问题描述 乱码是程序编码不统一,比如Java源代码是utf-8,编译是gbk,这时会乱码. 代码如下: org.testng.Repo ...

  7. js 将数字转换成人民币大写的方法

    //将数字转换成人民币大写的方法 var digitUppercase = function (n) { var fraction = ['角', '分']; var digit = [ '零', ' ...

  8. [转]自定义注释@interface的用法

    一.什么是注释     说起注释,得先提一提什么是元数据(metadata).所谓元数据就是数据的数据.也就是说,元数据是描述数据的.就象数据表中的字段一样,每个字段描述了这个字段下的数据的含义.而J ...

  9. JAVA-数据库之更新记录

    相关资料:<21天学通Java Web开发> 更新记录 StatementUpdate.jsp <%@ page language="java" contentT ...

  10. Python的可视化包 – Matplotlib 2D图表(点图和线图,.柱状或饼状类型的图),3D图表(曲面图,散点图和柱状图)

    Python的可视化包 – Matplotlib Matplotlib是Python中最常用的可视化工具之一,可以非常方便地创建海量类型地2D图表和一些基本的3D图表.Matplotlib最早是为了可 ...