Integrate Hibernate with Spring

In this post, we will learn how to integrate hibernate with spring. Earlier in this post, we have learned how to connect MySQL database with spring using JdbcTemplate. Now, we will do the same but using hibernate.

Note: If you find any difficulty while reading this post, we have kept the source code at the end of this post, so you can always refer to that anytime.

Below are the steps that we are going to follow while connecting hibernate with Spring MVC –

Adding dependencies –

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>8.0.22</version>
		</dependency>

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>4.3.8.Final</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>4.1.5.RELEASE</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>4.1.5.RELEASE</version>
		</dependency>

Whole pom.xml will look something like this –

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.codekru</groupId>
	<artifactId>demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<properties>
		<java.version>1.8</java.version>
		<spring.version>4.1.5.RELEASE</spring.version>
	</properties>
	<dependencies>
		<!-- Servlet API -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.1.0</version>
			<scope>provided</scope>
		</dependency>

		<!-- Spring Core -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<!-- Spring MVC -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>4.3.8.Final</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>4.1.5.RELEASE</version>
		</dependency>

		<!-- MySQL connector java -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>8.0.22</version>
		</dependency>

	</dependencies>
	<build>
		<finalName>demo</finalName>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-war-plugin</artifactId>
				<version>2.5</version>
				<configuration>
					<failOnMissingWebXml>false</failOnMissingWebXml>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<source>1.7</source>
					<target>1.7</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

Create a table in the database

In your MySQL database, please make a table like below, which will be used for various operations on db after integrating with Hibernate.

CREATE TABLE `title` (
 `id` int(11) AUTO_INCREMENT,
 `title_name` text,
 `description` text,
 PRIMARY KEY (`id`)
);

Create a model class

  • Create a Java package com.codekru.model. You can create the package by right clicking on the project folder and select New>Package.
  • We will create a model class here named Title.
package com.codekru.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "title")
public class Title {

	@Id
	@GeneratedValue
	private int id;
	
	@Column(name = "title_name")
	private String titleName;
	
	private String description;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getTitleName() {
		return titleName;
	}

	public void setTitleName(String titleName) {
		this.titleName = titleName;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

}

Now you must be thinking what does all these annotations mean? So, let’s look at that –

@Entity – This will tell that this class will be mapped to a table.
@Table – This is an optional annotation and If we don’t use this, then our class name will be considered as our table name, but we can override that by using its name attribute.
@Id – This will make the id variable as the primary key for the table and @GeneratedValue will auto-increment its value.
@Column – This is again an optional annotation and If we don’t define this, then our variable name will be used as the columnName for the table and we can always override it using the name attribute as we did with our titleName variable.

Create the configuration classes

  • Create a Java package com.codekru.config. You can create packages by right on the project folder and select New>Package.
  • Make your AppConfig class in com.codekru.config folder.
  • Now create a Datasource bean where we tell our database connection details.
	@Bean
	public DataSource dataSource() {

		DriverManagerDataSource dataSource = new DriverManagerDataSource();
		dataSource.setDriverClassName("com.mysql.jdbc.Driver");
		dataSource.setUrl("jdbc:mysql://localhost:3306/codekru");    // table name you made earlier in step 2
		dataSource.setUsername("root");    // username 
		dataSource.setPassword("root");    // password

		return dataSource;
	}

  • Create a sessionFactory Bean which will take Datasource bean as an argument. In this bean method, we tell Hibernate to generate SQL code specific to MySQL and declare our Title class:
	@Bean
	public SessionFactory sessionFactory(DataSource dataSource) {
		LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource);
		Properties props = new Properties();
		props.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
		props.put("hibernate.show_sql", "true");
		sessionBuilder.addProperties(props);
		sessionBuilder.addAnnotatedClass(Title.class);
		return sessionBuilder.buildSessionFactory();
	}
  • Add a HibernateTransactionManager bean –
	@Bean
	public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
		return new HibernateTransactionManager(sessionFactory);
	}
  • Whole AppConfig class will look like –
package com.codekru.config;

import java.util.Properties;

import javax.sql.DataSource;

import org.hibernate.SessionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import com.codekru.model.Title;

@EnableWebMvc
@Configuration
@EnableTransactionManagement
@ComponentScan(basePackages = { "com.codekru.controller", "com.codekru.dao" })
public class AppConfig {

	@Bean
	public DataSource dataSource() {

		DriverManagerDataSource dataSource = new DriverManagerDataSource();
		dataSource.setDriverClassName("com.mysql.jdbc.Driver");
		dataSource.setUrl("jdbc:mysql://localhost:3306/codekru");
		dataSource.setUsername("root");
		dataSource.setPassword("root");

		return dataSource;
	}

	@Bean
	public SessionFactory sessionFactory(DataSource dataSource) {
		LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource);
		Properties props = new Properties();
		props.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
		props.put("hibernate.show_sql", "true");
		sessionBuilder.addProperties(props);
		sessionBuilder.addAnnotatedClass(Title.class);
		return sessionBuilder.buildSessionFactory();
	}
	
	@Bean
	public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
		return new HibernateTransactionManager(sessionFactory);
	}
	
}

@Configuration – This declares it as a Spring Configuration class.
@EnableWebMvc – This enables Spring’s ability to receive and process web requests.
@ComponentScan – This scans the mentioned packages for Spring components.
@EnableTransactionManagement – It is used to enable transactional support, if you are using a spring boot project, then it is enabled by default.

  • And now in the same, create another class called ServletInitializer which will extend AbstractAnnotationConfigDispatcherServletInitializer and override its unimplemented methods.
package com.codekru.config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class ServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{

	@Override
	protected Class<?>[] getRootConfigClasses() {
		return new Class<?>[0];
	}

	@Override
	protected Class<?>[] getServletConfigClasses() {
		return new  Class<?>[] {AppConfig.class};
	}

	@Override
	protected String[] getServletMappings() {
		return new String[] {"/"};
	}

}

ServletInitializer is a configuration class for Spring’s servlet which replaces the standard web.xml file. It will be detected automatically by SpringServletContainerInitializer and extends the AbstractAnnotationConfigDispatcherServletInitializer abstract class and implements the required methods.

getServletMappings() – This declares the servlet root URI.
getServletConfigClasses() – This declares the Spring configuration classes. Here, we declared the AppConfig class that was previously defined.

Create DAO ( Data Access Object ) class

  • Create a Java package com.codekru.DAO. You can create the package by right on the project folder and select New>Package.
  • We will create a class here in this package named TitleDAO.
package com.codekru.dao;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.codekru.model.Title;



@Repository
public class TitleDAO {

	@Autowired
	SessionFactory sessionFactory;
	
	
	@Transactional
	public void add(Title title) {
	 sessionFactory.getCurrentSession().saveOrUpdate(title);
	}

	
}

We have autowired sessionFactory bean here which we have created earlier as we will be using the wonderful feature of DependencyInjection here. 😉

And now we only have to create a controller class which will call the add method of our TitleDAO class to save the object So, let’s get to that and finish this integration with hibernate.

Create a Controller class –

  • Create a Java package com.codekru.controller
  • Make a controller class called TitleController
package com.codekru.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.codekru.dao.TitleDAO;
import com.codekru.model.Title;

@Controller
public class TitleController {

	@Autowired
	TitleDAO titleDAO;
	
	@RequestMapping("saveTitle")
	@ResponseBody
	public String saveTitle() {
		Title title = new Title();
		title.setTitleName("Connecting hibernate with spring");
		title.setDescription("This will connect with hibernate with spring");
		titleDAO.add(title);
		return "Title name which is saved is: "+ title.getTitleName();
	}
	
	
}

And that’s it, we are done. Now you can build your code and go to this url http://localhost:8080/demo/saveTitle

Hope by now, you have integrated hibernate with your spring mvc project and if not, then you can see below source code provided and find out where you have been missing a semicolon 😉

Thank you for reading this article. If you find anything wrong or have any query, then you can write in comments or mail us at [email protected]

Liked the article? Share this on

Leave a Comment

Your email address will not be published.