duminică, 24 iulie 2016

Asserting the SQL statement count generated by Hibernate JPA via a Spring 4 MVC example

Before reading this post is strongly recommended to read How to assert the SQL statement count generated by Hibernate by Vlad Mihalcea.

The steps needed to assert the SQL statement count generated by Hibernate are:

1. Configure the DataSource-Proxy (this is needed because it will proxy your data source and can obtain important info such as the bind parameters values and number of executed SQLs).
2. Add the countQuery() when you build the proxy in order to instruct DataSource-Proxy to create a DataSourceQueryCountListener. This provides metrics information per HTTP request such as datasource name, number of database call, total query execution time and number of queries by type

public DataSource dataSource() {
 SLF4JQueryLoggingListener loggingListener = new SLF4JQueryLoggingListener();
 loggingListener.setQueryLogEntryCreator(new DefaultQueryLogEntryCreator());
 return ProxyDataSourceBuilder

3. Use the QueryCount directly, or even better use the db-util provided by Vlad Mihalcea. Among other things, here we have access to an out-of-the-box automated validator named, SQLStatementCountValidatorThis validator comes with the following static assertions: assertSelectCount(), assertInsertCount(), assertUpdateCount() and assertDeleteCount(). Simply place in your POM the following dependency:


4. In order to use this validator simply reset the QueryCount, execute the SQL statements and apply the proper assertions. Most likely, you will do this from an unit test, but just a quick sample we did it as below:

public void storeProducts() {
 Product p1 = new Product();

 Product p2 = new Product();

 Product p3 = new Product();


If the number of expected SQLs differs from the number of executed SQLs then the SQLStatementCountValidator will throw an excpetion of type SQLFooCountMismatchException where Foo is one of Select, Insert, Update, Delete depending on the SQL type. For example, if we test with:


then the message will be as:


Expected 1 statements but recorded 0 instead!  

NOTE: This was just a proof of concept being practically a pretty dummy example. In reality, you can use the assertion of the SQL statement count generated by Hibernate to see what happens behind fetching and finding the N+1 issues as the example created by Vlad Mihalcea here.

The complete application based on Hibernate JPA and Spring 4 MVC can be found here. The example should failed because we have inserted three records and asserted for 1.

Niciun comentariu:

Trimiteți un comentariu