Loading...

Spring Transaction Management with Jdbc Template Example

Faisal / Java,Spring

Transaction Management in simple terms means inserting / updating related data in the tables without loss. For example, we want to insert the data into 2 or 3 tables which are dependent on one another, then in such a case, it is very important to keep in mind data consistency. Every table needs to be updated without error, and if any table does not get updated due to any technical reasons whatsoever, then a rollback (removing inserted data) should be performed quickly.

In Spring, the framework allows us to achieve such feature very easily, which we can see in following example.

We will be using Spring JdbcTemplate with datasouce to insert data in 2 related tables (employee and address).

Before we jump into our Spring project, let’s do some database setup for our use.

Now let’s create a simple maven java project in Netbeans IDE, any IDE you are comfortable with. Our final project structure will look like below.

project_structure

We will be using spring jdbc API, which will be handled by spring-jdbc dependency injection. Along with spring core and mysql database dependencies. Let’s look at the pom.xml file.

Spring Maven Dependencies

Entity Model Classes

We have 2 classes, Employee and Address according to our database.

Employee.java

Address.java

Now we need our DAO and IMPL classes.

EmployeeDaoImpl.java

EmployeeDAO.java

Now final Run Class to test it all out:

Test.java

Leave a Comment