敲碎时间的人的个人专栏
上一篇

Spring hibernate JPA日志记录问题

广告
选中文字可对指定文章内容进行评论啦,→和←可快速切换按钮,绿色背景文字可以点击查看评论额。
大纲

今天我们来学习一下如何使用JPA的日志信息来记录执行的SQL语句,当然这里的SQL语句包括查询和修改。

我们先了解一般情况下的SQL是如何记录的,看看下面的配置

spring:
  jpa:
    database-platform: org.hibernate.dialect.H2Dialect
    hibernate:
      ddl-auto: update
    properties:
      hibernate:
        format_sql: true
    show_sql: true

这种类型的配置算是最普遍的配置的,当然,这个看着还行,会打印出一些SQL语句,但是不会把SQL的执行中的参数打印出来;

为了解决打印参数的问题,我们需要在log4j中配置,具体的操作就是,在log4j.properties

log4j.logger.org.hibernate.SQL = trace
log4j.logger.org.hibernate.type = trace

这样参数会连同sql语句一起打印出来;万事大吉,真的万事大吉吗?如果你按照上面的思路做,你会发现很多hibernate的日志都会打印出来,满屏幕都是日志。

我说的第二种方法是使用数据源代理,具体的操作很简单:

第一步,在pom.xml中增加一个配置依赖:

<dependency>
    <groupId>com.github.gavlyukovskiy</groupId>
    <artifactId>datasource-proxy-spring-boot-starter</artifactId>
    <version>1.8.1</version>
</dependency>

第二步,在application.yml中增加配置:

logging:
  level:
    net:
      ttddyy:
        dsproxy:
          listener: debug

好了,我们看看输出:

Name:dataSource, Connection:35, Time:0, Success:True
Type:Prepared, Batch:False, QuerySize:1, BatchSize:0
Query:["delete from us_follower where id=?"]
Params:[(10113)]

Name:dataSource, Connection:34, Time:0, Success:True
Type:Prepared, Batch:False, QuerySize:1, BatchSize:0
Query:["select follower0_.id as id1_7_, follower0_.avatar_url as avatar_u2_7_,
 follower0_.followable_id as followab5_7_, follower0_.name as name3_7_, 
 follower0_.user_id as user_id4_7_ from us_follower follower0_
  where (follower0_.name like ?) and follower0_.followable_id=1000 limit ?"]
Params:[(%yun900%,10)]

怎么样,看着还挺舒服吧,最主要是这个日志为我们提供了很多关键的信息:

比如,查询对应的数据源名称,连接编号,花费时间等等。

具体的字段说明请参考下面的表格:

KeyValue

Name

Name of ProxyDataSource

Connection

Connection ID

Time

How long query took to execute in ms.

Success

Query execution was successful or not.

Type

Type of statement (Statement/Prepared/Callable).

Batch

Batch execution.

QuerySize

Number of queries.

BatchSize

Number of batch.

Query

Query

Params

Query parameters

好了,要想优化自己的JPA,这是一个强烈推荐的工具。欢迎大家讨论学习。

版权声明:著作权归作者所有。