Spring MyBatis Log4j2打印SQL

一、版本

mybatis版本3.2.8,log4j2版本为2.2,采用spring集成mybatis

二、步骤

1、配置mybatis-config.xml 并将该文件放至resources文件夹下 内容如下:

<?xml version="1.0" encoding="UTF-8" ?>  
<!DOCTYPE configuration  
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"  
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <setting name="logImpl" value="LOG4J2" />
    </settings>
</configuration>

2、配置spring中mybatis配置

xml <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">中增加
<property name="configLocation" value="classpath:mybatis-config.xml" />
内容如下:

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="typeAliasesPackage" value="com.jd.jr.stock.domain"/>
        <!-- 加载mybatis的全局配置文件 -->
        <property name="configLocation" value="classpath:mybatis-config.xml" />
    </bean>

查看如下你的配置

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.jd.jr.stock.mapper"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>

将你配置的basePackage对应的value配置至log4j2.xml中

3、配置log4j2.xml

如下

<Loggers>
        <!-- 开启mybatis的sql日志, name和mybatis-config.xml的logPrefix一致 . 级别为debug或trace-->
        <AsyncLogger name="com.jd.jr.stock.mapper" level="Debug" additivity="true"/>

        <Root level="INFO">
            <AppenderRef ref="Console"/>
        </Root>
    </Loggers>

配置结束。

猜你喜欢

转载自blog.csdn.net/lhn1234321/article/details/81086273
今日推荐