Spring 4 MVC + Spring 3 Security + Hibernate 4 – integration with java annotations

Dear folks,

This may be the final post in the Spring 4 environment setup. We have already completed 3 out of 4 stages.

Last but not least, we do the hibernate integration in this post. Since ibatis is not doing good, Hibernate is monopolize the ORM market. Hence hibernate will be used in our next project. Here comes the integration. This tutorial assumes you have completed all the above steps and have the web project ready now.


Save this property file to the class path. I usually save at /src folder

jdbc.driverClassName = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/vriksha
jdbc.username = root
jdbc.password =
hibernate.dialect = org.hibernate.dialect.MySQLDialect
hibernate.show_sql = true
hibernate.format_sql = true

Changes to WebMvcConfigurerAdapter

We are doing important changes to the MVC Configurer. Please check all the methods and beans except getViewResolver(), which exists from the beginning.

package org.grassfield.conf;

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.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@ComponentScan(basePackages = { "org.grassfield.conf", "org.grassfield.common.dao", "org.grassfield.common.entity" })
public class ApplicationContextConfig extends WebMvcConfigurerAdapter {
    private Environment environment;

    @Bean(name = "viewResolver")
    public InternalResourceViewResolver getViewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        return viewResolver;

    @Bean(name = "datasource")
    public static DataSource dataSource() {
        BasicDataSource ds = new BasicDataSource();

        return ds;
    public LocalSessionFactoryBean sessionFactory(){
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setPackagesToScan(new String[]{"org.grassfield.common.entity"});
        return sessionFactory;
    private Properties hibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
        properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
        properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
        return properties;        
    public HibernateTransactionManager transactionManager(SessionFactory sessionFactory){
        HibernateTransactionManager tx = new HibernateTransactionManager();
        return tx;


Changes to HomeController

HomeController exists from the beginning. We are changing the method which handles the /protect url. This is secured by Spring Security. Please note the DAO call and ModelAndView population. Wiring Controller with a DAO is a bad practice. Don’t do it in your project, dear coders!

    public ModelAndView handleProtectedRequest(HttpServletRequest arg0,
            HttpServletResponse arg1) throws Exception {
        List<UserRole> userRoleList = this.userRoleDAO.list();
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("userRoleList", userRoleList);
        return modelAndView;


New DAO tier

We will be getting a list of user roles. Following is the interface for UserRoleDAO.

package org.grassfield.common.dao;

import java.util.List;

import org.grassfield.common.entity.UserRole;

public interface IUserRoleDAO {
    public List<UserRole> list();


The implementation goes like this. Please note the annotations.

package org.grassfield.common.dao;

import java.util.List;

import org.grassfield.common.entity.UserRole;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

public class UserRoleDAO implements IUserRoleDAO {
    private SessionFactory sessionFactory;
    public SessionFactory getSessionFactory() {
        return sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;

    public List<UserRole> list() {
        Session currentSession = this.sessionFactory.getCurrentSession();
        List<UserRole> list = currentSession.createQuery("From UserRole").list();
        return list;


And finally, our entity class is given below. Please note the annotations.

 * Package: com.eginnovations.common.entity 
 * FileName: UserRole.java
 * (c) 2010 eG Innovations private limited
 * Created by pandian on May 27, 2010 3:15:36 PM
package org.grassfield.common.entity;

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

 * The Class UserRole.
public class UserRole {
    @Id @GeneratedValue
    private Long id;
    private String name;
    private String emailPermission;
     * Gets the id.
     * @return the id
    public Long getId() {
        return id;
     * Sets the id.
     * @param id the new id
    public void setId(Long id) {
        this.id = id;


Now load the protected URL! You will see the list of the user roles.


Okay, This is more or less ready now. I need to do some refactoring. We can start building it by next weekend. Till then Bye!

spring-tool-suite-project-logo java8-logo image00110 Apache-Tomcat-logo



Hibernate demo



This post will help you to setup the environment to write your first hello world program with Hibernate!

  1. Get the hibernate distribution from their website. (as of now, I have hibernate-distribution-3.3.2.GA-dist.zip with me)
  2. Download the jars for commons-logging, asm and JDBC driver for your database.
  3. Start a java project in eclipse.
  4. Add all jars in hibernate distribution and other libraries mentioned in step 2.
  5. Prepare your hibernate configuration file
  6. Prepare your Data Transfer Object (DTO) and SQL table
  7. Prepare your hibernate mapping file for your DTO
  8. Start JDBC calls.

Library files needed

Almost all jars are being distributed. I have downloaded commons-logging and asm extra. Then I added the JDBC driver for mysql later. Nothing more (you want more????)



Preparation of Hibernate Configuration File

This file contains the DB configuration detail for Hibernate. Generally it follows the structure like this.

<?xml version=’1.0′ encoding=’utf-8′?>
<!DOCTYPE hibernate-configuration PUBLIC
“-//Hibernate/Hibernate Configuration DTD//EN”

<property name=”hibernate.connection.driver_class”>com.mysql.jdbc.Driver</property>
<property name=”hibernate.connection.url”>jdbc:mysql://localhost/test</property>
<property name=”hibernate.connection.username”>root</property>
<property name=”hibernate.connection.password”></property>
<property name=”hibernate.connection.pool_size”>1</property>
<property name=”show_sql”>true</property>
<property name=”dialect”>org.hibernate.dialect.MySQLDialect</property>
<property name=”hibernate.hbm2ddl.auto”>update</property>
<!– Mapping files –>
<mapping resource=”contact.hbm.xml”/>

name this as hibernate.cfg.xml and save it to your ‘src’ or source folder. On compilation it should go to your bin or classes or any other target folder.

Preparation of DTO and SQL table

Create  a table in your DBMS using the following structure

table structure

table structure

Write a java class that serves as the DTO for this table.

package hib;

public class Contact {
private String firstName;
private String lastName;
private String email;
private long id;

public String getFirstName() {
return firstName;
public void setFirstName(String firstName) {
this.firstName = firstName;
public String getLastName() {
return lastName;
public void setLastName(String lastName) {
this.lastName = lastName;
public String getEmail() {
return email;
public void setEmail(String email) {
this.email = email;
public long getId() {
return id;
public void setId(long id) {
this.id = id;

Preparation of hibernate mapping file for SQL table

We mentioned about mapping resource file. we need to create that file now. This is to tell the hibernate about the mapping between java and SQL table.

<mapping resource=”contact.hbm.xml”/>

Another XML is created as follows and named it as contact.hbm.xml

<?xml version=”1.0″?>
<!DOCTYPE hibernate-mapping PUBLIC
“-//Hibernate/Hibernate Mapping DTD 3.0//EN”

<class name=”hib.Contact” table=”CONTACT”>
<id name=”id” type=”long” column=”ID” >

<property name=”firstName”>
<column name=”FIRSTNAME” />
<property name=”lastName”>
<column name=”LASTNAME”/>
<property name=”email”>
<column name=”EMAIL”/>

Start Quering with Hibernate

This is the final step. Write a java program that invokes Hibernate and insert data into contact table.

package hib;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class FirstExample {

* @param args
public static void main(String[] args) {
//Hibernate Session is the main runtime interface between a Java application and Hibernate
Session session=null;
try {
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
session = sessionFactory.openSession();
System.out.println(“Inserting record”);
Contact contact = new Contact();

//save the contact information to the database
} catch (HibernateException e) {
if (session!=null)

Yes, Now we can start our program and see how the data is getting inserted.

console printing

console printing

Nice na.

Keep querying!

Ref: http://www.roseindia.net/hibernate/runninge-xample.shtml