Display parameters bound to query when fail happen

2019-08-04 13:18发布

问题:

Using Eclipselink with MySQL. When my entities are not validated properly and invalid data tries to leak into the database, the runtime exception is being thrown with following details:

Caused by: org.springframework.transaction.TransactionSystemException: Could not commit
JPA transaction; nested exception is javax.persistence.RollbackException: 
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.6.0.v20130815-a4708b6):
org.eclipse.persistence.exceptions.DatabaseException Internal Exception:
com.mysql.jdbc.MysqlDataTruncation: Data truncation: Data too long for column 'ip_address' at row 1
Error Code: 1406
Call: INSERT INTO statistics (action_name, created_at, ip_address, object_id, object_type, user_id) VALUES (?, ?, ?, ?, ?, ?)
     bind => [6 parameters bound]
Query: InsertObjectQuery(com.example.Statistics@3153ead4)"

My question is: how to discover and save in logs the values of the bound parameters from the exception? The 6 parameters bound does not help much.


EDIT:

Simple yet powerful solution is to override the toString() method of an entity. Then it will be used in logs, revealing details of the object that was about to be saved:

...
Call: INSERT INTO statistics (action_name, created_at, ip_address, object_id, object_type, user_id) VALUES (?, ?, ?, ?, ?, ?)
  bind => [6 parameters bound]
Query: InsertObjectQuery(Statistics{ID=null, ObjectType=PRODUCT, Action=VIEW, ObjectId=1, User=null, IP=someRandomInvalidTooLongIpAddress})"

However, I still wonder if there is any flag I can set to expand the X parameters bound phrase automatically.

回答1:

You can enable logging of parameters using the eclipselink.logging.parameters persistence property:

<property name="eclipselink.logging.parameters" value="true"/>

see http://wiki.eclipse.org/EclipseLink/Examples/JPA/Logging for more info on logging in EclipseLInk.