lundi 20 juin 2016

Appending caller information to SQL [duplicate]

This question already has an answer here:

I am working on a project for adding caller information to the SQL statements generated by hibernate. The generated SQL should look like this,

"/* com.foo.hibernate.App.testHibernate(App.java:34) */ select stock0_.STOCK_ID as STOCK1_0_, stock0_.STOCK_CODE as STOCK2_0_, stock0_.STOCK_NAME as STOCK3_0_ from test.stock stock0_"        

For getting the caller information(class name, file name, method name and line number), I am using a method named getStackTrace(),

public static void main(String[] args) {     
        // Code omitted.
        Query q = session.createQuery("From com.foo.hibernate.Stock");
        q.setComment(getStackTrace());
        q.list();
        // Code omitted.
}

private static String getStackTrace() {
        StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
        StackTraceElement topElement = stackTraceElements[2];
        return topElement.getClassName()+ "." + topElement.getMethodName() + "(" + topElement.getFileName() + ":" + topElement.getLineNumber() + ")";
}           

Though this approach looks good, for each SQL, we are dumping the stack trace of the current thread (might be a overhead). Is there a better way to get the caller information?

Aucun commentaire:

Enregistrer un commentaire