Spring JDBC Template
One of the most famous frameworks that we can find to access the database data is the Spring JDBC Template.
The code of this project can be found in here: https://github.com/uaihebert/SpringJdbcTemplateCrud
The Sprint JDBC Template uses natives queries like below:
As it is possible to see in the image above the query has a database syntax (I will be using MySQL). When we use a native SQL query it is possible to use all the database resources in an easy way.
We need an instance of the object JDBC Template (used to execute the queries), and to create the JDBC Template object we need to set up a datasource:
We can get the datasource now (thanks to the Spring injection) and create our JDBCTemplate:
PS.: All the XML code above and the JDBCTemplate instantiation could be replace by Spring injection and with a code bootstrap, just do a little research about the Spring features.
One thing that I did not liked is the INSERT statement with ID recover, it is very verbose:
With the KeyHolder class we can recover the generated ID in the database, unfortunately we need a huge code to do it.
The other CRUD functions are easier to use, like below:
Notice that to execute a SQL query it is very simple and results in a populated object, thanks to the RowMapper. The RowMapper is the engine that the JDBC Template uses to make easier to populate a class with data from the database. Take a look at the RowMapper code below:
The best news about the RowMapper is that it can be used in any query of the project. The developer that is responsible to write the logic that will populate the class data.
To finish this page, take a look below in the database DELETE and the database UPDATE statement:
About the Spring JDBC Template we can say:
Has a good support: Any search in the Internet will result in several pages with tips and bug fixes.
A lot of companies use it: several projects across the world use it
Be careful with different databases for the same project: The native SQL can became a problem with your project run with different databases. Several queries will need to be rewritten to adapt all the project databases.
Framework Knowledge: It is good to know the Spring basics, how it can be configured and used.
To those that does not know the Spring has several modules and in your project it is possible to use only the JDBC Template module. You could keep all the other modules/frameworks of your project and add only the necessary to run the JDBC Template.