Spring with JDBC Template by R4R Team

Spring with JDBC Template:-

Spring JdbcTemplate is a powerful mechanism to connect to the database and execute SQL queries. It internally uses JDBC api, but eliminates a lot of problems of JDBC API.


Spring framework has provided one abstraction layer on top of existing JDBC technology. We used to call this layer as Spring-JDBC. In this layer spring programmers will work with this abstraction layer and that layer will internally uses JDBC technology.


Spring framework uses DataSource interface to obtain the connection with database internally, i mean we will use any one of the following 2 implementation classes of DataSource interface.

1 Org.springframework.jdbc.datasource.DriverManagerDataSource [ class ]

2 Org.apache.commons.dbcp.BasicDataSource [ class ]


In spring config we need to configure the following 4 properties to obtain connection with database.

<bean id=”id” class=”org.springframework.datasource.DriverManagerDataSource”>

[ or ]

<bean id=”id” class=” org.apache.commons.dbcp.BasicDataSource”>

<property name=”driverClassName” value=”” />

<property name=”url” value=”” />

<property name=”username” value=”” />

<property name=”password” value=”” />

bean>


JdbcTemplate class provided the following 3 type of methods to execute SQL operations on the database

1 execute()

2 update()

3 query()


Problems of JDBC API :-

The problems of JDBC API are as follows:

1 We need to write a lot of code before and after executing the query, such as creating connection, statement, closing resultset, connection etc.

2 We need to perform exception handling code on the database logic.

3 We need to handle transaction.

4 Repetition of all these codes from one to another database logic is a time consuming task.


Advantage of Spring JdbcTemplate :-

Spring JdbcTemplate eliminates all the above mentioned problems of JDBC API. It provides you methods to write the queries directly, so it saves a lot of work and time.


JdbcTemplate class :-

It is the central class in the Spring JDBC support classes. It takes care of creation and release of resources such as creating and closing of connection object etc. So it will not lead to any problem if you forget to close the connection.


It handles the exception and provides the informative exception messages by the help of excepion classes defined in the org.springframework.dao package.


We can perform all the database operations by the help of JdbcTemplate class such as insertion, updation, deletion and retrieval of the data from the database.

Leave a Comment:
Search
Categories
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!