MyBatis打印输出SQL语句
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语句的更多相关文章
- mybatis实战教程(mybatis in action)之八:mybatis 动态sql语句
mybatis 的动态sql语句是基于OGNL表达式的.可以方便的在 sql 语句中实现某些逻辑. 总体说来mybatis 动态SQL 语句主要有以下几类:1. if 语句 (简单的条件判断)2. c ...
- 通过Log4j的DEBUG级别来显示mybatis的sql语句
为了更加方便调试sql语句,需要显示mybatis的sql语句. 网络上的一般方式都是通过log4j来实现,但是很多都有问题. 经过实验,以下代码能够保持正常:(只显示myb ...
- springmvc 项目完整示例04 整合mybatis mybatis所需要的jar包 mybatis配置文件 sql语句 mybatis应用
百度百科: MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBat ...
- Mybatis 动态Sql语句《常用》
MyBatis 的强大特性之一便是它的动态 SQL.如果你有使用 JDBC 或其他类似框架的经验,你就能体会到根据不同条件拼接 SQL 语句有多么痛苦.拼接的时候要确保不能忘了必要的空格,还要注意省掉 ...
- mybatis 动态sql语句(3)
mybatis 的动态sql语句是基于OGNL表达式的.可以方便的在 sql 语句中实现某些逻辑. 总体说来mybatis 动态SQL 语句主要有以下几类: 1. if 语句 (简单的条件判断) 2. ...
- mybatis 动态sql语句(1)
mybatis 的动态sql语句是基于OGNL表达式的.可以方便的在 sql 语句中实现某些逻辑. 总体说来mybatis 动态SQL 语句主要有以下几类: 1. if 语句 (简单的条件判断) 2. ...
- 【spring boot】【mybatis】spring boot中mybatis打印sql语句
spring boot中mybatis打印sql语句,怎么打印出来?[参考:https://www.cnblogs.com/sxdcgaq8080/p/9100178.html] 在applicati ...
- Java-MyBatis:MyBatis 3 | SQL 语句构建器类
ylbtech-Java-MyBatis:MyBatis 3 | SQL 语句构建器类 1.返回顶部 1. SQL语句构建器类 问题 Java程序员面对的最痛苦的事情之一就是在Java代码中嵌入SQL ...
- mybatis 打印sql 语句
拦截器 package com.cares.asis.mybatis.interceptor; import java.text.DateFormat; import java.util.Date; ...
随机推荐
- iframe自适应当前页面高度
<style type="text/css"> *{margin:0;padding:0;list-style-type:none;} </style> & ...
- Using curl to upload POST data with files
https://stackoverflow.com/questions/12667797/using-curl-to-upload-post-data-with-files ************* ...
- SecurityError: Blocked a frame with origin from accessing a cross-origin frame
问题描述:浏览器报错I am loading an <iframe> in my HTML page and trying to access the elements within it ...
- Android MediaScanner 总纲
1. MediaScanner HEAD 2. 应用层 MediaProvider packages\providers\MediaProvider (1) MediaProvider package ...
- 实践 ArcGIS Web 3D
ArcGIS 产品家族的 Web 3D 功能众多用户期待已久.从 ArcGIS 10.3.1 版本号開始,Esri 放了个大招,千呼万唤始出来的 Web 3D 功能,最终不再犹抱琵琶半遮面了. 那究竟 ...
- Error: Java heap space
在chd中 的hive中执行 (select count (*)) 或者mr程序都报Error: Java heap space 4.io.sort.mb 的作用 排序所使用的内存数量. 默认值 ...
- Deepin Linux已经做得相当不错了
很庆幸,用了MacBook Pro三四年后,还会想要用Linux做桌面,一方面说明自己还是年轻的,保持着愿意折腾的心态:另一方面,也确实发现macOS的桌面环境并不如传说中的稳定和好用. Deepin ...
- sc58x config
addip=set bootargs ${bootargs} ip=${ipaddr}:${serverip}:${gatewayip}:${netmask}:${hostname}:eth0:off ...
- USB入门
简述 USB(Universal Serial Bus)全称通用串口总线,USB为解决即插即用需求而诞生,支持热插拔.USB协议版本有USB1.0.USB1.1.USB2.0.USB3.1等,USB2 ...
- wps不记录打开打开的文件
“工具”中的“选项”后,进入选项界面,在“常规与保存”选项卡中把“最近文档管理列出文件”前面的勾取消或将后面的数字选为0.