Spring jdbc example

Posted on Updated on

Spring Framework is most famous java framework to build enterprise applications and database is integral part of enterprise applications. Spring framework provides excellent support for jdbc and other popular frameworks like hibernate, iBatis and many more. Here in this tutorial we will demonstrate example of CRUD operation using spring jdbc.
Technologies used in this examples are :

  1. JDK 1.7
  2. Maven as a build tool.
  3. Spring 4.1, however you can use lower versions of spring as well.
  4. Mysql as a database.

This example is created using Eclipse and maven plugin are used to create the basic folder structure for maven java project. We have added other files further to demonstrate this example. Our final folder structure looks like below image.

Spring jdbc

 

1) Spring JDBC dependencies.

Add spring jdbc and mysql dependencies into the pom.xml file.

2) Table creation in Database

For spring jdbc example we are using mysql database. Now create a Emp table using below database script.

3) Emp model object.

We need a model to store Emp data. So, create Emp model class as below.

4) Data Access Object (DAO) pattern

For DAO pattern, first we need to create one interface for CRUD application as below.

Now implement above interface and create EmpDaoImpl class which will be containing jdbc code for CRUD operation.

5) Spring configuration file.

We are using Spring framework 4.1. In case you are using above or below versions of spring, your applicationContext might be different. We have created dataSource bean which contain details of mysql driver and other properties like username and password which might be different if you have created database with different username and password. Below configuration file is annotation driven so it doesn’t have any other bean other than dataSource. In EmpDaoImpl class, dataSource bean is autowired to the local variable.

6) Load and Run Test class

We have created App.java class which contains simple logic for CRUD application. Run the main class.

7) Output

Stay tuned for more tutorials and examples.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.