Home  >  Spring

Spring HibernateTemplate Example

By Arvind Rai, February 24, 2022
This page will walk through Spring HibernateTemplate example.
1. Spring HibernateTemplate is a helper class that simplifies Hibernate data access code.
2. It automatically converts HibernateExceptions into DataAccessExceptions.
3. The central method of HibernateTemplate is execute that accepts HibernateCallback.
4. The execute method provides Hibernate session handling. It means neither the HibernateCallback implementation nor the calling code needs to explicitly care about retrieving/closing Hibernate Sessions, or handling Session lifecycle exceptions.
5. The HibernateTemplate is instantiated using SessionFactory either in @Configuration class or in XML configuration.
a. In @Configuration class.
@Bean
public HibernateTemplate hibernateTemplate() {
   return new HibernateTemplate(sessionFactory());
} 
b. In XML configuration.
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
     <constructor-arg name="sessionFactory" ref="sessionFactory"/>  
</bean> 
Now we will discuss using HibernateTemplate in detail.



Technologies Used

Find the technologies being used in our example.
1. Java 16
2. Spring 5.3.15
3. Spring Boot 2.6.3
4. MySQL 5.5

HibernateTemplate Methods

Find some of the methods of HibernateTemplate class.
1.
void clear() 
Remove all objects from the Session cache, and cancel all pending saves, updates and deletes.
2.
boolean contains(Object entity) 
Check whether the given object is in the Session cache.
3.
void delete(Object entity) 
Delete the given persistent instance.
4.
Filter enableFilter(String filterName) 
Return an enabled Hibernate org.hibernate.Filter for the given filter name.
5.
void evict(Object entity) 
Remove the given object from the Session cache.
6.
T execute(HibernateCallback<T> action) 
Execute the action specified by the given action object within a Session.
7.
List<?> findByCriteria(DetachedCriteria criteria) 
Execute a query based on a given Hibernate criteria object.
8.
List<T> findByExample(String entityName, T exampleEntity) 
Execute a query based on the given example entity object.
9.
T get(Class<T> entityClass, Serializable id) 
Return the persistent instance of the given entity class with the given identifier, or null if not found.
10.
T load(Class<T> entityClass, Serializable id) 
Return the persistent instance of the given entity class with the given identifier, throwing an exception if not found.
11.
List<T> loadAll(Class<T> entityClass) 
Return all persistent instances of the given entity class.
12.
T merge(String entityName, T entity) 
Copy the state of the given object onto the persistent object with the same identifier.
13.
void persist(String entityName, Object entity) 
Persist the given transient instance.
14.
Serializable save(Object entity) 
Persist the given transient instance.
15.
void saveOrUpdate(Object entity) 
Save or update the given persistent instance.
16.
void setMaxResults(int maxResults) 
Set the maximum number of rows for this HibernateTemplate.
17.
void update(Object entity) 
Update the given persistent instance, associating it with the current Hibernate Session.

HibernateTemplate in XML Configuration

Find the code to instantiate HibernateTemplate using XML configuration.
db-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context.xsd">

	<context:property-placeholder location="classpath:database.properties"/> 
	<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close" >
		<property name="url" value="${database.url}" />
		<property name="username" value="${database.root}" />
		<property name="password" value="${database.password}" />
	</bean>
	<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
	    <property name="dataSource" ref="dataSource"/>
	    <property name="hibernateProperties">
			<props>
			   <prop key="hibernate.dialect">${hibernate.dialect}</prop>
			   <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
			   <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
			</props>
	    </property>
            <property name="packagesToScan" value="com.concretepage.entity"/> 
	</bean>
	<bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
		<constructor-arg name="sessionFactory" ref="sessionFactory"/>  
	</bean>
	<bean id="personDAO" class="com.concretepage.PersonDAO">
	    <constructor-arg name="hibernateTemplate" ref="hibernateTemplate"/>
	</bean>
	<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
	    <property name="sessionFactory" ref="sessionFactory" />
	</bean>	
	<tx:annotation-driven transaction-manager="transactionManager" /> 		
</beans> 



HibernateTemplate in @Configuration class

Find the code to instantiate HibernateTemplate in @Configuration class.
DBConfig.java
package com.concretepage;
import java.io.IOException;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp2.BasicDataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@ComponentScan("com.concretepage") 
@PropertySource("classpath:database.properties")
public class DBConfig {
  @Autowired
  private Environment env;

  @Bean
  public HibernateTemplate hibernateTemplate() {
	return new HibernateTemplate(sessionFactory());
  }

  @Bean
  public SessionFactory sessionFactory() {
	LocalSessionFactoryBean lsfb = new LocalSessionFactoryBean();
	lsfb.setDataSource(getDataSource());
	lsfb.setPackagesToScan("com.concretepage.entity");
	lsfb.setHibernateProperties(hibernateProperties());
	try {
	  lsfb.afterPropertiesSet();
	} catch (IOException e) {
	  e.printStackTrace();
	}
	return lsfb.getObject();
  }

  @Bean
  public DataSource getDataSource() {
	BasicDataSource dataSource = new BasicDataSource();
	dataSource.setDriverClassName(env.getProperty("database.driver"));
	dataSource.setUrl(env.getProperty("database.url"));
	dataSource.setUsername(env.getProperty("database.root"));
	dataSource.setPassword(env.getProperty("database.password"));
	return dataSource;
  }

  @Bean
  public HibernateTransactionManager hibTransMan() {
	return new HibernateTransactionManager(sessionFactory());
  }

  private Properties hibernateProperties() {
	Properties properties = new Properties();
	properties.put("hibernate.dialect", env.getProperty("hibernate.dialect"));
	properties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
	properties.put("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
	return properties;
  }
} 
Now find the complete example.
pom.xml
<parent>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-parent</artifactId>
	<version>2.6.3</version>
	<relativePath />
</parent>
<properties>
	<java.version>16</java.version>
</properties>
<dependencies>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter</artifactId>
	</dependency>
	<dependency>
		<groupId> org.springframework.boot </groupId>
		<artifactId>spring-boot-starter-data-jpa</artifactId>
	</dependency>
	<dependency>
		<groupId>org.apache.commons</groupId>
		<artifactId>commons-dbcp2</artifactId>
		<version>2.9.0</version>
	</dependency>
	<dependency>
		<groupId>mysql</groupId>
		<artifactId>mysql-connector-java</artifactId>
		<version>5.1.31</version>
	</dependency>
</dependencies> 
database.properties
database.driver = com.mysql.jdbc.Driver
database.url = jdbc:mysql://localhost:3306/concretepage
database.root = root
database.password = cp

hibernate.dialect = org.hibernate.dialect.MySQLDialect
hibernate.hbm2ddl.auto = update
hibernate.show_sql = true 
Database Table
CREATE TABLE `person` (
	`pid` BIGINT(5) NOT NULL,
	`name` VARCHAR(100) NOT NULL,
	`city` VARCHAR(100) NOT NULL,
	PRIMARY KEY (`pid`)
) 
Person.java
package com.concretepage.entity;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity 
@Table(name= "person")
public class Person implements Serializable {
	private static final long serialVersionUID = 1L;
	@Id
	@Column(name="pid")
        private int pid;
	
	@Column(name = "name")
        private String name;
	
	@Column(name = "city")
        private String city;

        //Setters and Getters	
} 
PersonDAO.java
package com.concretepage;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;
import com.concretepage.entity.Person;

@Transactional
@Repository
public class PersonDAO {
  @Autowired
  private HibernateTemplate hibernateTemplate;

  public Person getPersonById(int pid) {
	return hibernateTemplate.get(Person.class, pid);
  }

  public List<Person> getAllPersons() {
	return hibernateTemplate.loadAll(Person.class);
  }

  public void addPerson(Person person) {
	hibernateTemplate.save(person);
  }

  public void updatePerson(Person person) {
	Person p = getPersonById(person.getPid());
	p.setName(person.getName());
	p.setCity(person.getCity());
	hibernateTemplate.update(p);
  }

  public void deletePerson(int pid) {
	hibernateTemplate.delete(getPersonById(pid));
  }
} 
SpringDemo.java
package com.concretepage;
import java.util.List;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.concretepage.entity.Person;

public class SpringDemo {
  public static void main(String... args) {
	AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
	ctx.register(DBConfig.class);
	ctx.refresh();
	PersonDAO personDAO = ctx.getBean(PersonDAO.class);

	// Add
	Person p1 = new Person();
	p1.setPid(100);
	p1.setName("Mahesh");
	p1.setCity("Varanasi");
	personDAO.addPerson(p1);

	Person p2 = new Person();
	p2.setPid(200);
	p2.setName("Ram");
	p2.setCity("Ayodhya");
	personDAO.addPerson(p2);

	// Get
	Person p = personDAO.getPersonById(200);
	System.out.println(p.getPid() + "|" + p.getName() + "|" + p.getCity());

	// Update
	p1.setName("Shiv");
	p1.setCity("Kashi");
	personDAO.updatePerson(p1);

	// Get All
	List<Person> list = personDAO.getAllPersons();
	list.forEach(ob -> System.out.println(ob.getPid() + "|" + ob.getName() + "|" + ob.getCity()));

	// Delete
	personDAO.deletePerson(100);
	personDAO.deletePerson(200);
  }
} 
Output
200|Ram|Ayodhya

100|Shiv|Kashi
200|Ram|Ayodhya 

Reference

Spring HibernateTemplate

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI










©2022 concretepage.com | Privacy Policy | Contact Us