Spring 4 + Hibernate 5 integration example with zero xml

Posted on April 23, 2017


In this example, we will learn how to develop a simple standalone application using Spring and Hibernate without any xml configuration.

Technologies and tools used for this application are -

  • Spring 4.3.7.RELEASE
  • Hibernate 5.2.9.Final
  • MySQL Connector 6.0.5
  • MySQL Server 5.7.12
  • Eclipse Neon.3
  • Maven 3.3.9
  • JavaSE 1.8

So let us proceed to write a simple standalone application using Spring and Hibernate.

Project structure

Review the following maven project structure.

spring-hibernate.png

Refer this article to learn - How to create a maven project in eclipse.

Jar dependencies

Add Spring, Hibernate and MySQL jar dependencies in pom.xml file.

pom.xml

<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 
  http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.boraji.tutorial.hibernate</groupId>
  <artifactId>spring-hibernate-example</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>spring-hibernate-tutorial</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <!-- Spring Context -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>4.3.7.RELEASE</version>
    </dependency>
    <!-- Spring ORM -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>4.3.7.RELEASE</version>
    </dependency>
    <!-- Mysql Connector -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>6.0.5</version>
    </dependency>
    <!-- Hibernate 5.2.9 Final -->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>5.2.9.Final</version>
    </dependency>
    <!-- Apache Commons DBCP -->
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-dbcp2</artifactId>
      <version>2.1.1</version>
    </dependency>
  </dependencies>

  <build>
    <sourceDirectory>src/main/java</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.5.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

Entity class

Create User.java file under com.boraji.tutorial.spring.entity package as follows.

User.java

package com.boraji.tutorial.spring.entity;

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

@Entity
@Table(name = "USERS")
public class User {

   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   private Long id;

   @Column(name = "FIRST_NAME")
   private String firstName;

   @Column(name = "LAST_NAME")
   private String lastName;

   @Column(name = "EMAIL")
   private String email;

   public User() {}
   
   public User(String firstName, String lastName, String email) {
      this.firstName = firstName;
      this.lastName = lastName;
      this.email = email;
   }

   //Getter and Setter methods
}

Data Access Object (DAO) class

Create @Repository classes under com.boraji.tutorial.spring.dao package as follows.

UserDao.java

package com.boraji.tutorial.spring.dao;

import java.util.List;

import com.boraji.tutorial.spring.entity.User;

public interface UserDao {
   void add(User user);
   List<User> listUsers();
}

UserDaoImp.java

package com.boraji.tutorial.spring.dao;

import java.util.List;

import javax.persistence.TypedQuery;

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

import com.boraji.tutorial.spring.entity.User;

/**
 * @author imssbora
 *
 */
@Repository
public class UserDaoImp implements UserDao {

   @Autowired
   private SessionFactory sessionFactory;

   @Override
   public void add(User user) {
      sessionFactory.getCurrentSession().save(user);
   }

   @Override
   public List<User> listUsers() {
      @SuppressWarnings("unchecked")
      TypedQuery<User> query=sessionFactory.getCurrentSession().createQuery("from User");
      return query.getResultList();
   }

}

 

Service class

Create @Service classes under com.boraji.tutorial.spring.service package as follows.

UserService,java

package com.boraji.tutorial.spring.service;

import java.util.List;

import com.boraji.tutorial.spring.entity.User;

public interface UserService {
    void add(User user);
    List<User> listUsers();
}

UserServiceImp.java

package com.boraji.tutorial.spring.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.boraji.tutorial.spring.dao.UserDao;
import com.boraji.tutorial.spring.entity.User;

/**
 * @author imssbora
 *
 */
@Service
public class UserServiceImp implements UserService {

   @Autowired
   private UserDao userDao;

   @Transactional
   @Override
   public void add(User user) {
      userDao.add(user);
   }

   @Transactional(readOnly = true)
   @Override
   public List<User> listUsers() {
      return userDao.listUsers();
   }

}

db.properties

Create db.properties configuration file under src/main/resources  folder for JDBC datasource and Hibernate properties.

db.properties

# MySQL properties
db.driver=com.mysql.cj.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/BORAJI
db.username=root
db.password=admin

# Hibernate properties
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update

Spring configuration

Create @Configuration class under com.boraji.tutorial.spring.config package.

Annotate this configuration class with @EnableTransactionManagement annotation to enable transaction management capability.

AppConfig.java

package com.boraji.tutorial.spring.config;

import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp2.BasicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScans;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.boraji.tutorial.spring.entity.User;
/**
 * @author imssbora
 *
 */
@Configuration
@PropertySource("classpath:db.properties")
@EnableTransactionManagement
@ComponentScans(value = { 
      @ComponentScan("com.boraji.tutorial.spring.dao"),
      @ComponentScan("com.boraji.tutorial.spring.service") 
    })
public class AppConfig {

   @Autowired
   private Environment env;

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

   @Bean
   public LocalSessionFactoryBean getSessionFactory() {
      LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean();
      factoryBean.setDataSource(getDataSource());
      
      Properties props=new Properties();
      props.put("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
      props.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));

      factoryBean.setHibernateProperties(props);
      factoryBean.setAnnotatedClasses(User.class);
      return factoryBean;
   }

   @Bean
   public HibernateTransactionManager getTransactionManager() {
      HibernateTransactionManager transactionManager = new HibernateTransactionManager();
      transactionManager.setSessionFactory(getSessionFactory().getObject());
      return transactionManager;
   }
}

 

Run application

Create a main class to test the above spring hibernate configuration.

MainApp.java

package com.boraji.tutorial.spring;

import java.util.List;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.boraji.tutorial.spring.config.AppConfig;
import com.boraji.tutorial.spring.entity.User;
import com.boraji.tutorial.spring.service.UserService;

/**
 * @author imssbora
 *
 */
public class MainApp {
   public static void main(String[] args) {
      AnnotationConfigApplicationContext context = 
            new AnnotationConfigApplicationContext(AppConfig.class);

      UserService userService = context.getBean(UserService.class);

      // Add Users
      userService.add(new User("Sunil", "Bora", "[email protected]"));
      userService.add(new User("David", "Miller", "[email protected]"));
      userService.add(new User("Sameer", "Singh", "[email protected]"));
      userService.add(new User("Paul", "Smith", "[email protected]"));

      // Get Users
      List<User> users = userService.listUsers();
      for (User user : users) {
         System.out.println("Id = "+user.getId());
         System.out.println("First Name = "+user.getFirstName());
         System.out.println("Last Name = "+user.getLastName());
         System.out.println("Email = "+user.getEmail());
         System.out.println();
      }

      context.close();
   }
}

Output

Hibernate: create table USERS (id bigint not null auto_increment, EMAIL varchar(255), FIRST_NAME varchar(255), LAST_NAME varchar(255), primary key (id)) engine=MyISAM
Hibernate: insert into USERS (EMAIL, FIRST_NAME, LAST_NAME) values (?, ?, ?)
Hibernate: insert into USERS (EMAIL, FIRST_NAME, LAST_NAME) values (?, ?, ?)
Hibernate: insert into USERS (EMAIL, FIRST_NAME, LAST_NAME) values (?, ?, ?)
Hibernate: insert into USERS (EMAIL, FIRST_NAME, LAST_NAME) values (?, ?, ?)
Hibernate: select user0_.id as id1_0_, user0_.EMAIL as EMAIL2_0_, user0_.FIRST_NAME as FIRST_NA3_0_, user0_.LAST_NAME as LAST_NAM4_0_ from USERS user0_
Id = 1
First Name = Sunil
Last Name = Bora
Email = [email protected]

Id = 2
First Name = David
Last Name = Miller
Email = [email protected]

Id = 3
First Name = Sameer
Last Name = Singh
Email = [email protected]

Id = 4
First Name = Paul
Last Name = Smith
Email = [email protected]
Download Sources