JPA使用p6spy打印SQL,将参数'?'自动替换

Tips:
springboot版本:2.0.8.RELEASE
jdk:1.8

在使用JPA的时候,show-sql显示不是那么友好,为了得到可执行的SQL语句,找到了p6spy这个工具。网上很多版本老旧,在新版中会出现各种报错,所以整理了个工具,希望能快速帮到大家,避免走弯路。 至于为什么有这个需求,一个是因为JPA打印出来很多?号,不能进行参数替换,还有就是因为懒,巨懒。

  1. 导入maven依赖

    p6spy
    p6spy
    3.8.6

  1. 修改数据源配置,只需更改driver-class-nameurl,以pg,mysql为例

pg

spring:
  datasource:
#    driver-class-name: org.postgresql.Driver
    driver-class-name: com.p6spy.engine.spy.P6SpyDriver
#    url: jdbc:postgresql://localhost:5432/postgres
    url: jdbc:p6spy:postgresql://localhost:5432/postgres
    username: postgres
    password: 123456

mysql

spring:
  datasource:
    url: jdbc:p6spy:mysql://localhost:3306/xxx?useUnicode=true&useSSL=false&serverTimezone=UTC
    username: root
    password: 123456
    driver-class-name: com.p6spy.engine.spy.P6SpyDriver

3.新增配置 spy.properties 到resources下

logMessageFormat=com.p6spy.engine.spy.appender.CustomLineFormat
customLogMessageFormat=sql -> %(sqlSingleLine)
appender=com.p6spy.engine.spy.appender.StdoutLogger
#appender=com.p6spy.engine.spy.appender.FileLogger
#appender=com.p6spy.engine.spy.appender.Slf4JLogger
#customLogMessageFormat=%(sqlSingleLine)
#customLogMessageFormat=%(currentTime)|%(executionTime)|%(category)|connection%(connectionId)|%(sqlSingleLine)

这里只是为了快速得到一个可执行的SQL,更高级的用法还请自行研究,哈哈。

给出一个JPA结合p6spy打印SQL的例子。感觉不错点个赞吧。

sql -> drop table if exists book cascade
sql -> create table book (id  serial not null, author varchar(255), name varchar(255), time time, primary key (id))
sql -> insert into book (author, name, time) values ('1', '1', '2019-12-02T10:53:23.941+0800')
sql -> select currval('book_id_seq')
sql -> insert into book (author, name, time) values ('2', '2', '2019-12-02T10:53:23.941+0800')
sql -> select currval('book_id_seq')
sql -> insert into book (author, name, time) values ('3', '3', '2019-12-02T10:53:23.941+0800')
sql -> select currval('book_id_seq')
sql -> insert into book (author, name, time) values ('4', '4', '2019-12-02T10:53:23.941+0800')
sql -> select currval('book_id_seq')
sql -> select book0_.id as id1_0_, book0_.author as author2_0_, book0_.name as name3_0_, book0_.time as time4_0_ from book book0_ where book0_.author='1' and book0_.name='1'

你可能感兴趣的:(JPA使用p6spy打印SQL,将参数'?'自动替换)