Is there a way to capture the executed SQL statements in Hibernate and Ibatis then save them to database?

StackOverflow https://stackoverflow.com/questions/19951471

Question

One of the requirements on my current project is to be able to log the SQL statement generated by either Hibernate or Ibatis, and save them to a specific table (on SQLServer), so an administrator can come back and see what queries were run and who ran them, or even reuse the statements on demand. While I don't agree with this approach, I would like to know if there actually exists a library that can achieve this. I am using Spring framework for my web application.

Was it helpful?

Solution 2

If you want to catch all queries of a middleware like Hibernate or Ibatis, the simplest way is to use SQL Server profiler or to create a trace with SQLTrace stored procedures (sp_trace_create, sp_trace_setevent). With SQL Profiler you can save traces directly to a table, with SQLTrace stored procedure who produces a trc file, you will have to insert them in your table with sql statements. they are lot of examples on the web, for example here SQL Profiler have an option to generate the SQLTrace SQL script once you have defined your trace (File/export)

The SQL Profiler is in the developper edition but not in the Express edition. SQLTrace stored procedures are in all editions (IIRC).

You can generate the trace script on your developper edition and run it on your express edition. You can also create a stored proc that create and start the trace on server startup.

OTHER TIPS

There are 3rd party SQL Server tools that can capture T-SQL statements, and store them for later manipulation and analysis, such as Idera SQL Compliance Manager and ApexSQL Comply

Disclaimer: I work as a Product Support Engineer at ApexSQL

You can do it on the server, with database audit if you have the enterprise edition of SQL Server. Or you can use Extended Events. You just need to filter by the application name, which should mention the ORM. To help you further, please provide the version and edition of SQL Server.

I know a way though it's not easy to implement. Make a custom DataSource - a wrapper over a real DataSource like Apache BasicDataSource. It will intercept getConnection calls and wrap Connection returned by the target DataSource. This wrapped Connections will intercept createStatement / createPreparedStatement calls and wrap Statements / PreparedStatements returned. The Statement wrapper can now intercept SQL executions and log them.

Yet another way to do it would be to enable SQL statement logging in the Hibernate configuration settings, and then "hoover" the statements out of the log files.

But I think that a database-server-side solution is probably the best, because it can also captures queries and updates performed using the database's interactive query tool.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top