Spring JDBC and Hibernate Tutorial

Spring JDBC Implementation in an Application

Welcome to the Java Spring JDBC and Spring Hibernate tutorial offered by Simplilearn. The tutorial is a part of the Java Certification Training Course.

Let us begin with the objectives of Spring JDBC and Hibernate tutorial in the next section.

Objectives

The spring JDBC and spring hibernation tutorial explains about:

  • Spring JDBC/DAO (Data Access Object)

  • The implementation of Spring JDBC in an application

  • The Integration of Spring with Hibernate

  • How to create applications using spring hibernate template

  • Spring JDBC Transaction Management

Let us learn the Spring JDBC or Data Access Object (DAO) in the next section.

Spring JDBC /DAO (Data Access Object)

The Spring JDBC /DAO (Data Access Object) is used to build a Data Access Layer of an enterprise application. It is a mechanism to connect to the database and execute SQL queries. The database-related logic has to be placed in separate classes called DAO classes.

In the next section, let us look at the comparison between JDBC and Spring JDBC.

JDBC vs. Spring JDBC

Let us now look at the comparison between JDBC and Spring JDBC.

Difference based on

JDBC

Spring JDBC

Transaction Management Logic:

(enable or disable transactions declaratively)

It doesn’t support

Spring JDBC supports

Distribution based Transaction Management

It doesn’t support

Spring JDBC supports

Annotation-based transaction management

It doesn’t support

Spring JDBC supports

Resource Allocating Logic

Connection, Statement, and Prepared statement have to be allocated explicitly by the developer in JDBC.

Spring provides org.springframework.jdbcTemplateobject. It abstracts the Database Resource Allocation Logic.

Resource Releasing Logic

In JDBC, the developer explicitly writes the logic to release the database resources.

Spring provides org.springframework.jdbc.core.jdbcTemplateobject.

Exception Handling

JDBC throws java.sql.SQLException. There won’t be specific exceptions for specific problems.

Spring provides Fine Grind Exception Handling mechanism to deal with Database.

The image below shows the DAO classes.

The DAO classes are shown connecting to the spring JDBC framework, which is an additional layer which then connects to the JDBC API and finally talks to the database.

In the next section, let us look at the advantage of spring JDBC API.

The Advantage of Spring JDBC API

The advantage of using Spring JDBC is that -

  • It provides the capability to establish the connection and interact with the database.

  • It simplifies the development of JDBC, Hibernate, JPA, and JDO.

  • It provides multiple templates to interact with the database including the JdbcTemplate, HibernateTemplate, JDOTemplate, JPATemplate.

In the next section, we will look at the terminologies of spring JDBC API (Connection Pooling).

Terminologies of Spring JDBC API (Connection Pooling)

The terminologies of Spring JDBC API  when a connection is opened and closed (when required) in an application, the object utilization becomes difficult and the cost of the implementation increases. In such cases, connection pooling is used.

It is a mechanism of pre-creating a group of database connections and keeping them in cache memory for use and reuse. It provides high performance and efficient resource management.

In the next section, let us look at the terminologies of spring JDBC API (java.sql.DataSource).

Terminologies of Spring JDBC API (java.sql.DataSource)

This is an interface which is an object-oriented representation of the connection pooling. It is a connection factory for Java application. It is an alternative for driver manager and provides Database connections to the Java application.

The following connection pooling mechanisms provide its implementation classes -

  • >Apache BasicDatasource

  • >Spring DriverManagerDatasource and

  • >C3pOComboPooleDatasource.

In the next section, we will look at the Spring JDBC Template.

Spring JDBC Template

Spring JDBC provides a class called “JdbcTemplate” to handle the common logic. JdbcTemplate is an abstraction of the JDBC technology.

The methods provided by JdbcTemplate are -

  • For insert(), update(), and delete() methods of JDBC, Spring JdbcTemplate provides update() method

  • For findByAccno(), findByBalance(), findAll(), rowCount() methods of JDBC, Spring Template provides query(), queryForInt(), queryObject(), queryForMap(), and queryForList()

  • To handle batch updates, JdbcTemplate has convenient methods.

In the next section, let us look at the Spring JDBC Template Methods.

Spring JDBC Template Methods

The table below shows the JDBC template methods.

public int update (String query)

public int update (String query)

public int update (String query)

inserts, updates, and deletes records using PreparedStatement using given arguments

public void execute (String query)

executes DDL query

public T execute (String SQL, PreparedStatementCallback action)

executes the query by using PreparedStatementcallback

public T query (String SQL, ResultSetExtractorrse)

fetches records using ResultSetExtractor

public List query (String SQL, RowMapperrse)

fetches records using RowMapper

In the next section, we will talk about Spring JDBC implementation in an application.

Implementing Spring JDBC in an Application

To implement spring JDBC in an application, we have to -

  1. Create database and table in the database

  2. Create Java projects in eclipse

  3. Create the Spring Bean class(POJO class)

  4. Create a DAO class

  5. Configure DataSource and the spring bean spring configuration XML file

  6. Create the Spring Bean or Spring container either by XmlBeanFactory or ApplicationContext

The steps for implementing Spring JDBC in an application;

Step 1:

First, we create a database and the table in the database.

The syntax to create the database is: create database databasename;

The syntax to create the table with the respective columns :

CREATE TABLE table_name (column1 datatype, column2 datatype, column3 datatype,....);

Step 2:

The second step involves creating a Java project in Eclipse.

Step 3:

In the third step, we consider a user class that has three member variables. They are id, name, and salary.

public class User {

private int id;

private String name;

private float salary;

//no-argand parameterized constructors

//getters and setters

}

Step 4:

In the fourth step, we create a DAO class.

public class UserDao {

private JdbcTemplate jdbcTemplate;

public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {

this.jdbcTemplate = jdbcTemplate;

}

public int saveUser(User e){

String query="insert into user values(

'"+e.getId()+"','"+e.getName()+"','"+e.getSalary()+"')";

return jdbcTemplate.update(query);

}

public int updateUser(User e){

String query="update user set

name='"+e.getName()+"',salary='"+e.getSalary()+"' where id='"+e.getId()+"' ";

return jdbcTemplate.update(query);

}

public int deleteUser(User e){

String query="delete from user where id='"+e.getId()+"' ";

return jdbcTemplate.update(query);

}

Here, we create an object of JDBC template and set it in the constructor. Then, to save, update, and delete the user, we write the string queries and pass them to the jdbcTemplate.update method.

Step 5:

The fifth step is to configure DataSource and the SpringBean spring configuration XML file. In this step, the JDBC driver can be used to establish connectivity to the database during development or basic unit or integration testing.

Spring has two data source classes:

  • DriverManagerDataSource: which returns a new connection every time a connection is required, and

  • SingleConnectionDataSource: which returns the same connection every time a connection is required

Next, we configure DataSource and spring bean by the XML file. The configuration can be explained in steps as follows:

  1. The bean id is configured to the DriverManagerDataSource,

  2. The property driverClassName is configured to the Driver,

  3. The property URL is configured to the URL of the database, username, and password.

  4. The bean id jdbcTemplate configures to the JdbcTemplate class, and the dataSource gets a reference name.

  5. We then create a bean id for injecting the UserDao class and

  6. Lastly, we reference the jdbcTemplate.

<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">

<property name="driverClassName" value="com.mysql.jdbc.Driver" />

<property name="url" value="jdbc:mysql:3306//localhost/databasename" />

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

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

</bean>

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">

<property name="dataSource" ref="ds"></property>

</bean>

<bean id="edao" class="UserDao">

<property name="jdbcTemplate" ref="jdbcTemplate"></property>

</bean>

Step 6:

The last step creates a spring container either by XmlBeanFactory or ApplicationContext.

public class Test {

public static void main(String[] args) {

ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");

UserDao dao=(UserDao)ctx.getBean("edao");

int status=dao.saveUser(new User(101,"John",350000));

System.out.println(status);

}

Here, we are making use of the ApplicationContext. We pass the XML file reference, we get the UserDao class injected we then save the user information and print the status.

Why Integrate Spring with Hibernate?

Spring framework provides integration with Hibernate, Toplink, Ibatis, and JPA. Spring can be integrated with hibernate:

  • In large applications, this integration makes the maintenance very easy.

  • When integrated, caching and other performance tuning is handled automatically.

  • When the database can be changed easily without affecting the application code.

Integrating hibernate application with spring avoids creating the hibernate.cfg.xml file. All information can be contained in an applicationContext.xml file.

In the next section, we will look at integrating spring with hibernate.

Integrating Spring with Hibernate

The steps in integrating spring with hibernate are given below. They are-

  • Configuring application.xml.

  • Configuring sessionfactory using the class AnnotationSessionFactoryBean.

  • Define HibernateTemplate by passing sessionfactory.

  • For the database transaction, define HibernateTransactionManager. Using the transaction manager, configure AOP.

In the next section, we will look at the hibernateTemplate class.

HibernateTemplate Class

HibernateTemplate is a helper class that simplifies Hibernate data access code. It automatically converts HibernateExceptions into DataAccessExceptions by following the org.springframework.dao exception hierarchy.

The structure of the hibernate template class is given below:

org.springframework.orm.hibernate3

public class HibernateTemplate

extends HibernateAccessor

implements HibernateOperations

Here, the public class HibernateTemplate extends HibernateAccessor implements HibernateOperations.

In the next section, we will look at the methods of the hibernateTemplate class.

Methods of HibernateTemplate Class

There are multiple methods available, let us understand them from the table given below.

Method

Description

void persist(Object entity)

Persists the given object.

Serializable save(Object entity)

Persists the given object and returns id.

void saveOrUpdate(Object entity)

Persists or updates the given object. If id is found, it updates the record; otherwise, it saves the record.

void update(Object entity)

Updates the given object

void delete(Object entity)

Deletes the given object on the basis of id.

Object get(Class entityClass, Serializable id)

Returns the persistent object on the basis of given id.

Object load(Class entityClass, Serializable id)

Returns the persistent object on the basis of given id.

List loadAll(Class entityClass)

Returns all the persistent objects.

In the next section, we will look at creating an application using spring hibernateTemplate.

Creating Application using Spring Hibernate Template

In order to create applications using spring hibernate template, we have to -

  • Create a database.

  • Create Java project in eclipse.

  • Create User.java file. It is the persistent class.

  • Create UserDao.java file. It is the DAO class that uses HibernateTemplate.

  • Create applicationContext.xml file. It contains information of DataSource, SessionFactory, etc.

  • Create Test.Java file. It calls methods of UserDaoclass.

Let us now look at the steps involved in creating an application using spring hibernate template.

Step 1:

The first step is to Create database.
The syntax to create a database is: create database databasename;

Step 2:

The second step is to create the java project in eclipse as discussed before.

Step 3:

The third step is to create the create the User.java file and mark it with the entity and id tag as an annotation.

@Entity

public class User implements Serializable {

private static final long serialVersionUID= 1L;

@Id

private int id;

private String name;

// constructor

// public setter and getter methods

}

Step 4:

The fourth step is to UserDao.java file.

public class PageDao {

private HibernateTemplate hibernateTemplate;

public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {

this.hibernateTemplate= hibernateTemplate;

}

public void persist(){

User u1= new User(1,"Ankita");

hibernateTemplate.save(u1);

User u2= new User(2,"Renu");

hibernateTemplate.save(u2);

}

}

Here we create the hibernateTemplate instead of the jdbcTemplate and this is how we will persist the information using the persist method.

Step 5:

In the fifth step, we create the application Context.xml file then we create the sessionFactory so that we can register the bean. Thus, we are registering the template by providing the template reference to the EmployeeDao bean.

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

<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>

<property name="url" value="jdbc:mysql://localhost:3306/database"></property>

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

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

</bean>

<bean id="mysessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">

<property name="dataSource" ref="dataSource"></property>

<property name="mappingResources">

<list>

<value>employee.hbm.xml</value>

</list>

</property>

<property name="hibernateProperties">

<props>

<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>

<prop key="hibernate.hbm2ddl.auto">update</prop>

<prop key="hibernate.show_sql">true</prop>

</props>

</property>

</bean>

<bean id="template" class="org.springframework.orm.hibernate3.HibernateTemplate">

<property name="sessionFactory" ref="mysessionFactory"></property>

</bean>

<bean id="d" class="com.javatpoint.EmployeeDao">

<property name="template" ref="template"></property>

</bean>

</beans>

Step 6:

In the sixth step, we create the main where we load the XML file. We will pass the bean id to get the bean object and we persist the information.

public class SpringDemo {

public static void main(String... args) {

ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");

PageDao pd=(PageDao) context.getBean("pageDao");

pd.persist();

}

}

Output:

Hibernate: insert into User (name, id) values (?, ?)

Hibernate: insert into User (name, id) values (?, ?)

In the next section, we will learn spring JDBC transaction management.

Spring JDBC Transaction Management

Spring provides extensive support for transaction management. This helps developers to focus on business logic rather than worrying about the integrity of the data in case of any system failures.

Spring provides an abstract layer on top of different transaction management APIs. It helps application developers to focus on the business problem, without having to know much about the underlying transaction management APIs.

In the next section, let us learn about ACID.

Interested to learn more about Java? Enroll in our Java Certification Training Course today.

ACID

The concept of transactions can be described using the following four key properties known as ACID. ACID stands for -

  • Atomicity - Atomicity requires that each transaction be ‘all or nothing’. If one part of the transaction fails, then the entire transaction fails, and the database state is left unchanged.

  • Consistency  - Consistency property ensures that any transaction will bring the database from one valid state to another.

  • Isolation - Isolation property ensures that the concurrent execution of transactions results in a system state that would be obtained if transactions were executed serially, that is, one after the other.

  • Durability -  Durability property ensures that once a transaction has been committed, it will remain so, even in the event of power loss, crashes, or errors.

In the next section, let us look at the transaction management interface

Transaction Management Interface

PlatformTransactionManager is a general interface for all Spring transaction managers:

public interface PlatformTransactionManager {

TransactionStatus getTransaction ( TransactionDefinitiondefinition);

throws TransactionException;

void commit(TransactionStatus status) throws TransactionException;

void rollback(TransactionStatus status) throws TransactionException;

}

Spring has several built-in implementations of this interface that can be used with different transaction management APIs like DataSourceTransactionManager, HibernateTransactionManager, and JpaTransactionManager.

In the next section, let us look at the methods of the platform transaction manager.

Methods of the Platform Transaction Manager

The table below shows the various methods along with their description.

Method

Description

TransactionStatus getTransaction(TransactionDefinitiondefinition)

This method returns a currently active transaction or creates a new one, according to the specified propagation behavior.

void commit(TransactionStatus status)

This method commits the given transaction, with regard to its status.

void rollback(TransactionStatus status)

This method performs a rollback of the given transaction.

In the next section, we will learn about the TransactionDefinition interface.

TransactionDefinition Interface

TransactionDefinition is the core interface of the transaction support in Spring, and it is defined as follows:

public interface TransactionDefinition {

int getPropagationBehavior();

int getIsolationLevel();

String getName();

int getTimeout();

boolean isReadOnly();

}

In the next section, we will look at the methods of TransactionDefinition.

Methods of TransactionDefinition

The table below shows the various methods along with its description.

Method

Description

int getPropagationBehavior()

This method returns the propagation behavior. Spring offers all of the transaction propagation options offered by EJB CMT.

int getIsolationLevel()

This method returns the degree to which this transaction is isolated from the work of other transactions.

String getName()

This method returns the name of the transaction.

int getTimeout()

This method returns the time (in seconds) in which the transaction must complete.

boolean isReadOnly()

This method queries whether the transaction is read-only.

In the next section, we will look at the TransactionStatus interface.

TransactionStatus Interface

TransactionStatus interface provides a simple way for transactional code to control transaction execution and query transaction status.

public interface TransactionStatus extends SavepointManager {

boolean isNewTransaction();

boolean hasSavepoint();

void setRollbackOnly();

boolean isRollbackOnly();

boolean isCompleted();

}

In the next section, we will learn the methods of TransactionStatus.

Methods of TransactionStatus

The table below shows the various methods along with the description.

Method

Description

boolean hasSavepoint()

This method returns whether this transaction internally carries a savepoint, i.e., has been created as nested transaction based on a savepoint.

boolean isCompleted()

This method returns whether this transaction is completed, i.e., whether it has already been committed or rolled back.

boolean isNewTransaction()

This method returns true in case the present transaction is new.

boolean isRollbackOnly()

This method returns whether the transaction has been marked as rollback-only.

void setRollbackOnly()

This method sets the transaction as rollback-only.

In the next section, we will learn the types of transaction management.

Types of Transaction Management

Spring supports two types of transaction management:

  1. Programmatic transaction management

  2. Declarative transaction management

Now let us learn about each of them in detail.

Programmatic Transaction Management

Let us look at the functions of Programmatic transaction management:

  • It manages transaction with the help of programming.

  • It uses PlatformTransactionManager directly to implement the programmatic approach to implement transactions and create an instance of TransactionDefinition with the appropriate transaction attributes.

  • Once the TransactionDefinition is created, you can start your transaction by calling getTransaction()method, which returns an instance of TransactionStatus.

  • The TransactionStatus objects help in tracking the current status of the transaction.

  • Programmatic Transaction Management uses commit() method of PlatformTransactionManager to commit the transaction.

Declarative Transaction Management

Let us look at the functions of Declarative transaction management:

  • Separates transaction management from the business code

  • Allows you to manage the transaction with the help of the configuration instead of hardcoding in your source code

  • Uses annotations or XML- based configurations to manage the transactions

  • Uses <tx:advice/> tag. This creates a transaction-handling advice and defines a Pointcut that matches all methods needed for the transaction at the same time

Summary

Let us summarize what we have learned in this lesson:

  • Spring JDBC is used to build the Data Access Layer of the enterprise application. It is a mechanism to connect to the database and execute SQL queries. The database-related logic has to placed in separate classes called DAO classes.

  • Connection pooling is a mechanism of pre-creating a group of database connections and keeping them in cache memory for use and reuse. It provides high performance and efficient resource management.

  • Spring supports two types of transaction management: Programmatic transaction management and Declarative transaction management.

Conclusion

With this, we come to an end to the Spring JDBC and Spring Hibernate tutorial. In the next chapter, we will look at Spring MVC.

Find our Java Certification Training Online Classroom training classes in top cities:


Name Date Place
Java Certification Training 20 Jul -31 Aug 2019, Weekend batch Your City View Details
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.

Request more information

For individuals
For business
Name*
Email*
Phone Number*
Your Message (Optional)
We are looking into your query.
Our consultants will get in touch with you soon.

A Simplilearn representative will get back to you in one business day.

First Name*
Last Name*
Email*
Phone Number*
Company*
Job Title*