Skip to content

Instantly share code, notes, and snippets.

@bdeterling
Created May 12, 2013 14:02
Show Gist options
  • Save bdeterling/5563683 to your computer and use it in GitHub Desktop.
Save bdeterling/5563683 to your computer and use it in GitHub Desktop.
Method to extract parameters from Hibernate query
private Map getParameters(Object obj) {
Map parameters = new HashMap();
Object query = null;
if (obj instanceof AbstractQueryImpl) {
query = obj;
} else {
return parameters;
}
try {
AbstractQueryImpl q = (AbstractQueryImpl) query;
Field f = AbstractQueryImpl.class.getDeclaredField("namedParameters");
f.setAccessible(true);
Map namedParameters = (Map) f.get(q);
for (Iterator iter = namedParameters.entrySet().iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
String name = (String) entry.getKey();
TypedValue value = (TypedValue) entry.getValue();
Object o = value.getValue();
String valueStr;
if (o instanceof Calendar) {
valueStr = DateUtils.printCal((Calendar) o);
} else {
valueStr = o.toString();
}
parameters.put(name, valueStr);
}
f = AbstractQueryImpl.class.getDeclaredField("namedParameterLists");
f.setAccessible(true);
namedParameters = (Map) f.get(q);
for (Iterator iter = namedParameters.entrySet().iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
String name = (String) entry.getKey();
TypedValue value = (TypedValue) entry.getValue();
Object o = value.getValue();
String valueStr;
if (o instanceof Calendar) {
valueStr = DateUtils.printCal((Calendar) o);
} else {
valueStr = o.toString();
}
if (valueStr.length() > 500) {
valueStr = valueStr.substring(0, 500) + "...";
}
parameters.put(name, valueStr);
}
} catch (Throwable t) {
if (logger.isDebugEnabled()) {
logger.debug("Error intercepting query parameters", t);
}
}
return parameters;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment