Display parameters bound to query when fail happens

喜欢而已 提交于 2020-01-05 08:02:55

问题


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.



来源:https://stackoverflow.com/questions/21453302/display-parameters-bound-to-query-when-fail-happens

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!