Spring MVC Hibernate with Tomcat JNDI


Let us implement Spring based web application which uses Hibernate and JNDI datasource with Tomcat


Please refer JNDI overview article to have basic understanding of JNDI.

Step 1

Create hibernate project

Please refer Hibernate setup in eclipse article on how to do it.

Project structure

springmvc_jndi_proj_structure1
springmvc_jndi_proj_structure2

Step 2

Update pom.xml with required dependencies

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2.   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  3.   <modelVersion>4.0.0</modelVersion>
  4.   <groupId>SpringMVCHibernateJNDI</groupId>
  5.   <artifactId>SpringMVCHibernateJNDI</artifactId>
  6.   <packaging>war</packaging>
  7.   <version>0.0.1-SNAPSHOT</version>
  8.   <name>SpringMVCHibernateJNDI Maven Webapp</name>
  9.   <url>http://maven.apache.org</url>
  10.  <properties>
  11.         <org.springframework.version>4.2.0.RELEASE</org.springframework.version>
  12.     </properties>
  13.     <dependencies>
  14.         <dependency>
  15.             <groupId>junit</groupId>
  16.             <artifactId>junit</artifactId>
  17.             <version>3.8.1</version>
  18.             <scope>test</scope>
  19.         </dependency>
  20.        
  21.         <dependency>
  22.             <groupId>org.springframework</groupId>
  23.             <artifactId>spring-webmvc</artifactId>
  24.             <version>${org.springframework.version}</version>
  25.         </dependency>
  26.         <dependency>
  27.             <groupId>org.hibernate</groupId>
  28.             <artifactId>hibernate-core</artifactId>
  29.             <version>5.2.6.Final</version>
  30.         </dependency>
  31.          <dependency>
  32.             <groupId>mysql</groupId>
  33.             <artifactId>mysql-connector-java</artifactId>
  34.             <version>6.0.5</version>
  35.         </dependency>
  36.         <dependency>
  37.             <groupId>org.springframework</groupId>
  38.             <artifactId>spring-tx</artifactId>
  39.             <version>${org.springframework.version}</version>
  40.         </dependency>
  41.        
  42.         <dependency>
  43.             <groupId>org.springframework</groupId>
  44.             <artifactId>spring-orm</artifactId>
  45.             <version>${org.springframework.version}</version>
  46.         </dependency>
  47.        
  48.         <dependency>
  49.             <groupId>javax.servlet</groupId>
  50.             <artifactId>servlet-api</artifactId>
  51.             <version>2.5</version>
  52.         </dependency>
  53.         <dependency>
  54.             <groupId>javax.servlet.jsp</groupId>
  55.             <artifactId>jsp-api</artifactId>
  56.             <version>2.1</version>
  57.         </dependency>
  58.         <dependency>
  59.             <groupId>javax.servlet</groupId>
  60.             <artifactId>jstl</artifactId>
  61.             <version>1.2</version>
  62.         </dependency>
  63.     </dependencies>
  64.   <build>
  65.     <finalName>SpringMVCHibernateJNDI</finalName>
  66.   </build>
  67. </project>
<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>SpringMVCHibernateJNDI</groupId>
  <artifactId>SpringMVCHibernateJNDI</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>SpringMVCHibernateJNDI Maven Webapp</name>
  <url>http://maven.apache.org</url>
 <properties>
		<org.springframework.version>4.2.0.RELEASE</org.springframework.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
		
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>5.2.6.Final</version>
		</dependency>
		 <dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>6.0.5</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>
		
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>
		
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.1</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
	</dependencies>
  <build>
    <finalName>SpringMVCHibernateJNDI</finalName>
  </build>
</project>

Step 3

Update web.xml file with Dispatcher servlet

  1. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2.     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
  3.     version="3.1">
  4.   <display-name>Archetype Created Web Application</display-name>
  5.   <!-- Spring MVC dispatcher servlet -->
  6.     <servlet>
  7.         <servlet-name>mvc-dispatcher</servlet-name>
  8.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  9.         <init-param>
  10.             <param-name>contextConfigLocation</param-name>
  11.             <param-value>
  12.             /WEB-INF/spring-mvc.xml
  13.             </param-value>
  14.         </init-param>
  15.         <load-on-startup>1</load-on-startup>
  16.     </servlet>
  17.     <servlet-mapping>
  18.         <servlet-name>mvc-dispatcher</servlet-name>
  19.         <url-pattern>/</url-pattern>
  20.     </servlet-mapping>
  21.  
  22.     <listener>
  23.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  24.     </listener>
  25.     <context-param>
  26.         <param-name>contextConfigLocation</param-name>
  27.         <param-value>
  28.             /WEB-INF/spring-mvc.xml
  29.         </param-value>
  30.     </context-param>
  31. </web-app>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    version="3.1">
  <display-name>Archetype Created Web Application</display-name>
  <!-- Spring MVC dispatcher servlet -->
    <servlet>
        <servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>
            /WEB-INF/spring-mvc.xml
            </param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
 
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/spring-mvc.xml
        </param-value>
    </context-param>
</web-app>

Step 4

Configure data source in Server and create the JNDI name.

We need to add below entry in tomcat’s server.xml

  1. <Resource name="javainsimpleway"
  2.       global="javainsimpleway"
  3.       auth="Container"
  4.       type="javax.sql.DataSource"
  5.       driverClassName="com.mysql.jdbc.Driver"
  6.       url="jdbc:mysql://localhost:3306/javainsimpleway"
  7.       username="root"
  8.       password="root"
  9.       maxActive="100"
  10.       maxIdle="20"
  11.       minIdle="5"
  12.       maxWait="10000"/>
<Resource name="javainsimpleway" 
      global="javainsimpleway" 
      auth="Container" 
      type="javax.sql.DataSource" 
      driverClassName="com.mysql.jdbc.Driver" 
      url="jdbc:mysql://localhost:3306/javainsimpleway" 
      username="root" 
      password="root" 
      maxActive="100" 
      maxIdle="20" 
      minIdle="5" 
      maxWait="10000"/>

Step 5

Update the Resource name in web.xml or context.xml

We need to make the Resource linking either in web.xml or context.xml of Tomcat server as below

Let us add the below details in context.xml of Tomcat

  1. <ResourceLink name="javainsimpleway"
  2.               global="javainsimpleway"
  3.               auth="Container"
  4.               type="javax.sql.DataSource" />
<ResourceLink name="javainsimpleway"
              global="javainsimpleway"
              auth="Container"
              type="javax.sql.DataSource" />

Step 6

Create Spring-mvc.xml with JNDI configuration

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
  4.     xmlns:context="http://www.springframework.org/schema/context"
  5.     xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
  6.     xmlns:jee="http://www.springframework.org/schema/jee"
  7.     xsi:schemaLocation="http://www.springframework.org/schema/beans
  8.        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
  9.        http://www.springframework.org/schema/context
  10.        http://www.springframework.org/schema/context/spring-context-3.2.xsd
  11.        http://www.springframework.org/schema/mvc
  12.        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
  13.        http://www.springframework.org/schema/tx
  14.        http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
  15.        http://www.springframework.org/schema/jee
  16.        http://www.springframework.org/schema/jee/spring-jee-3.0.xsd">
  17.  
  18.     <context:component-scan base-package="com.kb" />
  19.     <mvc:annotation-driven />
  20.     <context:property-placeholder location="classpath:database.properties" />
  21.  
  22.     <jee:jndi-lookup id="dataSource" jndi-name="java:/comp/env/javainsimpleway"
  23.         expected-type="javax.sql.DataSource" />
  24.  
  25.     <bean id="viewResolver"
  26.         class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  27.         <property name="prefix" value="/WEB-INF/pages/" />
  28.         <property name="suffix" value=".jsp" />
  29.     </bean>
  30.  
  31.     <bean class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"
  32.         id="sessionFactory">
  33.         <property name="dataSource" ref="dataSource"></property>
  34.         <property name="annotatedClasses">
  35.             <list>
  36.                 <value>com.kb.model.Employee</value>
  37.             </list>
  38.         </property>
  39.         <property name="hibernateProperties">
  40.             <props>
  41.                 <prop key="hibernate.dialect">${hibernate.dialect}</prop>
  42.                 <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
  43.                 <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}  </prop>
  44.             </props>
  45.         </property>
  46.     </bean>
  47.    
  48.  
  49.     <bean id="messageSource"
  50.         class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
  51.         <property name="basename" value="classpath:messages" />
  52.         <property name="defaultEncoding" value="UTF-8" />
  53.     </bean>
  54.  
  55.     <bean id="localeResolver"
  56.         class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
  57.         <property name="defaultLocale" value="en" />
  58.     </bean>
  59.  
  60.     <mvc:interceptors>
  61.         <bean id="localeChangeInterceptor"
  62.             class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
  63.             <property name="paramName" value="language" />
  64.         </bean>
  65.     </mvc:interceptors>
  66.  
  67. </beans>
<?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:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:jee="http://www.springframework.org/schema/jee"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
        http://www.springframework.org/schema/jee
        http://www.springframework.org/schema/jee/spring-jee-3.0.xsd">

	<context:component-scan base-package="com.kb" />
	<mvc:annotation-driven />
	<context:property-placeholder location="classpath:database.properties" />

	<jee:jndi-lookup id="dataSource" jndi-name="java:/comp/env/javainsimpleway"
		expected-type="javax.sql.DataSource" />

	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/pages/" />
		<property name="suffix" value=".jsp" />
	</bean>

	<bean class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"
		id="sessionFactory">
		<property name="dataSource" ref="dataSource"></property>
		<property name="annotatedClasses">
			<list>
				<value>com.kb.model.Employee</value>
			</list>
		</property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">${hibernate.dialect}</prop>
				<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
				<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}  </prop>
			</props>
		</property>
	</bean>
	

	<bean id="messageSource"
		class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
		<property name="basename" value="classpath:messages" />
		<property name="defaultEncoding" value="UTF-8" />
	</bean>

	<bean id="localeResolver"
		class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
		<property name="defaultLocale" value="en" />
	</bean>

	<mvc:interceptors>
		<bean id="localeChangeInterceptor"
			class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
			<property name="paramName" value="language" />
		</bean>
	</mvc:interceptors>

</beans>


We have added below code for JNDI

  1. <jee:jndi-lookup id="dataSource" jndi-name="java:/comp/env/javainsimpleway"
  2.         expected-type="javax.sql.DataSource" />
<jee:jndi-lookup id="dataSource" jndi-name="java:/comp/env/javainsimpleway"
		expected-type="javax.sql.DataSource" />


This will do the JNDI lookup in web container to obtain the connection from the pool and inject it to Hibernate sessionfactory.

The resource name must be same as jndi lookup name which is javainsimpleway in our case.

Step 7

Create the Employee class

  1. package com.kb.model;
  2.  
  3. import javax.persistence.Column;
  4. import javax.persistence.Entity;
  5. import javax.persistence.GeneratedValue;
  6. import javax.persistence.GenerationType;
  7. import javax.persistence.Id;
  8. import javax.persistence.Table;
  9.  
  10. @Entity
  11. @Table(name="Employee")
  12. public class Employee {
  13.     @Id
  14.     @GeneratedValue(strategy = GenerationType.SEQUENCE)
  15.     @Column(name = "Employee_Id")
  16.     private Integer employeeId;
  17.    
  18.     @Column(name = "FirstName")
  19.     private String firstName;
  20.    
  21.     @Column(name = "LastName")
  22.     private String lastName;
  23.    
  24.     @Column(name = "Age")
  25.     private Integer age;
  26.    
  27.     @Column(name = "Education")
  28.     private String education;
  29.    
  30.     @Column(name = "Salary")
  31.     private Double salary;
  32.    
  33.     public Integer getEmployeeId() {
  34.         return employeeId;
  35.     }
  36.     public void setEmployeeId(Integer employeeId) {
  37.         this.employeeId = employeeId;
  38.     }
  39.     public String getFirstName() {
  40.         return firstName;
  41.     }
  42.     public void setFirstName(String firstName) {
  43.         this.firstName = firstName;
  44.     }
  45.     public String getLastName() {
  46.         return lastName;
  47.     }
  48.     public void setLastName(String lastName) {
  49.         this.lastName = lastName;
  50.     }
  51.     public Integer getAge() {
  52.         return age;
  53.     }
  54.     public void setAge(Integer age) {
  55.         this.age = age;
  56.     }
  57.     public String getEducation() {
  58.         return education;
  59.     }
  60.     public void setEducation(String education) {
  61.         this.education = education;
  62.     }
  63.     public Double getSalary() {
  64.         return salary;
  65.     }
  66.     public void setSalary(Double salary) {
  67.         this.salary = salary;
  68.     }
  69. }
package com.kb.model;

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="Employee")
public class Employee {
	@Id
	@GeneratedValue(strategy = GenerationType.SEQUENCE)
	@Column(name = "Employee_Id")
	private Integer employeeId;
	
	@Column(name = "FirstName")
	private String firstName;
	
	@Column(name = "LastName")
	private String lastName;
	
	@Column(name = "Age")
	private Integer age;
	
	@Column(name = "Education")
	private String education;
	
	@Column(name = "Salary")
	private Double salary;
	
	public Integer getEmployeeId() {
		return employeeId;
	}
	public void setEmployeeId(Integer employeeId) {
		this.employeeId = employeeId;
	}
	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 Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	public String getEducation() {
		return education;
	}
	public void setEducation(String education) {
		this.education = education;
	}
	public Double getSalary() {
		return salary;
	}
	public void setSalary(Double salary) {
		this.salary = salary;
	}
}

Step 8

Create the controller class

  1. package com.kb.controllers;
  2.  
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.stereotype.Controller;
  5. import org.springframework.ui.Model;
  6. import org.springframework.web.bind.annotation.RequestMapping;
  7. import org.springframework.web.bind.annotation.RequestMethod;
  8.  
  9. import com.kb.service.EmployeeService;
  10.  
  11. @Controller
  12. public class EmployeeController {
  13.    
  14.     @Autowired
  15.     private EmployeeService employeeService;
  16.  
  17.     @RequestMapping(value = "/employees", method = RequestMethod.GET)
  18.     public String listemployees(Model model) {
  19.         model.addAttribute("employeeList", employeeService.listEmployees());
  20.         return "employee";
  21.     }
  22.    
  23.     @RequestMapping(value = "/insertSampleEmployees", method = RequestMethod.GET)
  24.     public String insertSampleEmployees(Model model) {
  25.         try {
  26.             employeeService.insertSampleEmployees();
  27.             model.addAttribute("responseMsg", "Successfully inserted sample data");
  28.         } catch (Exception e) {
  29.             model.addAttribute("responseMsg", "Failed to insert sample data");
  30.         }
  31.         return "result";
  32.     }
  33. }
package com.kb.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.kb.service.EmployeeService;

@Controller
public class EmployeeController {
	
	@Autowired
	private EmployeeService employeeService;

	@RequestMapping(value = "/employees", method = RequestMethod.GET)
	public String listemployees(Model model) {
		model.addAttribute("employeeList", employeeService.listEmployees());
		return "employee";
	}
	
	@RequestMapping(value = "/insertSampleEmployees", method = RequestMethod.GET)
	public String insertSampleEmployees(Model model) {
		try {
			employeeService.insertSampleEmployees();
			model.addAttribute("responseMsg", "Successfully inserted sample data");
		} catch (Exception e) {
			model.addAttribute("responseMsg", "Failed to insert sample data");
		}
		return "result";
	}
}

Step 9

Create the EmployeeService interface

  1. package com.kb.service;
  2.  
  3. import java.util.List;
  4.  
  5. import com.kb.model.Employee;
  6.  
  7. public interface EmployeeService {
  8.    
  9.     public List<Employee> listEmployees();
  10.    
  11.     public void insertSampleEmployees();
  12.  
  13. }
package com.kb.service;

import java.util.List;

import com.kb.model.Employee;

public interface EmployeeService {
	
	public List<Employee> listEmployees();
	
	public void insertSampleEmployees();

}

Step 10

Create the EmployeeServiceImpl class

  1. package com.kb.service;
  2.  
  3. import java.util.List;
  4.  
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.stereotype.Service;
  7.  
  8. import com.kb.dao.EmployeeDAO;
  9. import com.kb.model.Employee;
  10.  
  11. @Service
  12. public class EmployeeServiceImpl implements EmployeeService {
  13.    
  14.     @Autowired
  15.     private EmployeeDAO employeeDAO;
  16.  
  17.     @Override
  18.     public List<Employee> listEmployees() {
  19.         return this.employeeDAO.listEmployees();
  20.     }
  21.  
  22.     @Override
  23.     public void insertSampleEmployees() {
  24.         employeeDAO.insertSampleEmployees();
  25.     }
  26.    
  27. }
package com.kb.service;

import java.util.List;

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

import com.kb.dao.EmployeeDAO;
import com.kb.model.Employee;

@Service
public class EmployeeServiceImpl implements EmployeeService {
	
	@Autowired
	private EmployeeDAO employeeDAO;

	@Override
	public List<Employee> listEmployees() {
		return this.employeeDAO.listEmployees();
	}

	@Override
	public void insertSampleEmployees() {
		employeeDAO.insertSampleEmployees();
	}
	
}

Step 11

Create the EmployeeDAO interface

  1. package com.kb.dao;
  2.  
  3. import java.util.List;
  4.  
  5. import com.kb.model.Employee;
  6.  
  7. public interface EmployeeDAO {
  8.    
  9.     public List<Employee> listEmployees();
  10.    
  11.     public void insertSampleEmployees();
  12.  
  13. }
package com.kb.dao;

import java.util.List;

import com.kb.model.Employee;

public interface EmployeeDAO {
	
	public List<Employee> listEmployees();
	
	public void insertSampleEmployees();

}

Step 12

Create the EmployeeDAOImpl class

  1. package com.kb.dao;
  2.  
  3. import java.util.List;
  4.  
  5. import org.hibernate.Session;
  6. import org.hibernate.SessionFactory;
  7. import org.hibernate.Transaction;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.stereotype.Repository;
  10.  
  11. import com.kb.model.Employee;
  12.  
  13. @Repository
  14. public class EmployeeDAOImpl implements EmployeeDAO{
  15.    
  16.     @Autowired
  17.      private SessionFactory sessionFactory;
  18.    
  19.  
  20.     @SuppressWarnings("unchecked")
  21.     @Override
  22.     public List<Employee> listEmployees() {
  23.         Session session = sessionFactory.openSession();
  24.         List<Employee> EmployeesList = session.createQuery("from Employee").list();
  25.         return EmployeesList;
  26.     }
  27.    
  28.     public void insertSampleEmployees(){
  29.         // Get session from Sesson factory
  30.         Session session = sessionFactory.openSession();
  31.  
  32.         // Begin transaction
  33.         Transaction t = session.beginTransaction();
  34.        
  35.         //Create Employee  data
  36.         Employee employee1 = new Employee();
  37.         employee1.setFirstName("John");
  38.         employee1.setLastName("KC");
  39.         employee1.setAge(28);
  40.         employee1.setEducation("PG");
  41.         employee1.setSalary(25000d);
  42.        
  43.         Employee employee2 = new Employee();
  44.         employee2.setFirstName("Jacob");
  45.         employee2.setLastName("JC");
  46.         employee2.setAge(30);
  47.         employee2.setEducation("PG");
  48.         employee2.setSalary(30000d);
  49.        
  50.         Employee employee3 = new Employee();
  51.         employee3.setFirstName("Martin");
  52.         employee3.setLastName("A");
  53.         employee3.setAge(24);
  54.         employee3.setEducation("UG");
  55.         employee3.setSalary(20000d);
  56.        
  57.         Employee employee4 = new Employee();
  58.         employee4.setFirstName("Peter");
  59.         employee4.setLastName("M");
  60.         employee4.setAge(25);
  61.         employee4.setEducation("UG");
  62.         employee4.setSalary(22000d);
  63.        
  64.         Employee employee5 = new Employee();
  65.         employee5.setFirstName("Roshan");
  66.         employee5.setLastName("B");
  67.         employee5.setAge(29);
  68.         employee5.setEducation("PG");
  69.         employee5.setSalary(45000d);
  70.        
  71.        
  72.         session.save(employee1);
  73.         session.save(employee2);
  74.         session.save(employee3);
  75.         session.save(employee4);
  76.         session.save(employee5);
  77.  
  78.         t.commit();
  79.        
  80.         session.close();
  81.     }
  82.  
  83. }
package com.kb.dao;

import java.util.List;

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

import com.kb.model.Employee;

@Repository
public class EmployeeDAOImpl implements EmployeeDAO{
	
	@Autowired
	 private SessionFactory sessionFactory;
	

	@SuppressWarnings("unchecked")
	@Override
	public List<Employee> listEmployees() {
		Session session = sessionFactory.openSession();
		List<Employee> EmployeesList = session.createQuery("from Employee").list();
		return EmployeesList;
	}
	
	public void insertSampleEmployees(){
		// Get session from Sesson factory
		Session session = sessionFactory.openSession();

		// Begin transaction
		Transaction t = session.beginTransaction();
		
		//Create Employee  data
		Employee employee1 = new Employee();
		employee1.setFirstName("John");
		employee1.setLastName("KC");
		employee1.setAge(28);
		employee1.setEducation("PG");
		employee1.setSalary(25000d);
		
		Employee employee2 = new Employee();
		employee2.setFirstName("Jacob");
		employee2.setLastName("JC");
		employee2.setAge(30);
		employee2.setEducation("PG");
		employee2.setSalary(30000d);
		
		Employee employee3 = new Employee();
		employee3.setFirstName("Martin");
		employee3.setLastName("A");
		employee3.setAge(24);
		employee3.setEducation("UG");
		employee3.setSalary(20000d);
		
		Employee employee4 = new Employee();
		employee4.setFirstName("Peter");
		employee4.setLastName("M");
		employee4.setAge(25);
		employee4.setEducation("UG");
		employee4.setSalary(22000d);
		
		Employee employee5 = new Employee();
		employee5.setFirstName("Roshan");
		employee5.setLastName("B");
		employee5.setAge(29);
		employee5.setEducation("PG");
		employee5.setSalary(45000d);
		
		
		session.save(employee1);
		session.save(employee2);
		session.save(employee3);
		session.save(employee4);
		session.save(employee5);

		t.commit();
		
		session.close();
	}

}

Step 13

Create database.properties

hibernate.dialect=org.hibernate.dialect.MySQLDialect

hibernate.show_sql=true

hibernate.hbm2ddl.auto=update

Step 14

Create messages_en.properties


EmployeeID=Employee Id

FirstName=First Name

LastName=Last Name

Age=Age

Education=Education

Salary=Salary

employeeList=Employee List

Step 15

Create the employee.jsp page

  1. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
  2. <%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>
  3. <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
  4. <%@ page session="false" %>
  5. <html>
  6. <head>
  7.     <title>Employee Page</title>
  8.     <style type="text/css">
  9.  
  10.         .empTable  {border-collapse:collapse;border-spacing:0;border-color:#ccc;}
  11.  
  12.         .empTable td{
  13.                               font-family:Arial, sans-serif;font-size:16px;padding:10px 5px;
  14.                               border-style:solid;border-width:2px;overflow:hidden;word-break:normal;
  15.                               border-color:#ccc;color:#00FF00;background-color:#FF0000;
  16.                             }
  17.  
  18.         .empTable th{
  19.                               font-family:Arial, sans-serif;font-size:16px;font-weight:normal;
  20.                               padding:10px 5px;border-style:solid;border-width:2px;overflow:hidden;
  21.                               word-break:normal;border-color:#ccc;color:#000000;background-color:#FF4500;
  22.                             }
  23.  
  24.         .empTable .empTable-4eph{background-color:#C0C0C0}
  25.  
  26.     </style>
  27. </head>
  28. <body>
  29.  
  30. <c:if test="${not empty employeeList}">
  31. <h3><spring:message code="employeeList"/></h3>
  32.     <table class="empTable">
  33.     <tr>
  34.         <th width="80"><spring:message code="EmployeeID"/></th>
  35.         <th width="120"><spring:message code="FirstName"/></th>
  36.         <th width="120"><spring:message code="LastName"/></th>
  37.         <th width="120"><spring:message code="Age"/></th>
  38.         <th width="120"><spring:message code="Education"/></th>
  39.         <th width="120"><spring:message code="Salary"/></th>
  40.     </tr>
  41.     <c:forEach items="${employeeList}" var="employee">
  42.         <tr>
  43.             <td>${employee.employeeId}</td>
  44.             <td>${employee.firstName}</td>
  45.             <td>${employee.lastName}</td>
  46.             <td>${employee.age}</td>
  47.             <td>${employee.education}</td>
  48.             <td>${employee.salary}</td>
  49.         </tr>
  50.     </c:forEach>
  51.     </table>
  52. </c:if>
  53. </body>
  54. </html>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@ page session="false" %>
<html>
<head>
	<title>Employee Page</title>
	<style type="text/css">

		.empTable  {border-collapse:collapse;border-spacing:0;border-color:#ccc;}

		.empTable td{
                              font-family:Arial, sans-serif;font-size:16px;padding:10px 5px;
                              border-style:solid;border-width:2px;overflow:hidden;word-break:normal;
                              border-color:#ccc;color:#00FF00;background-color:#FF0000;
                            }

		.empTable th{
                              font-family:Arial, sans-serif;font-size:16px;font-weight:normal;
                              padding:10px 5px;border-style:solid;border-width:2px;overflow:hidden;
                              word-break:normal;border-color:#ccc;color:#000000;background-color:#FF4500;
                            }

		.empTable .empTable-4eph{background-color:#C0C0C0}

	</style>
</head>
<body>

<c:if test="${not empty employeeList}">
<h3><spring:message code="employeeList"/></h3>
	<table class="empTable">
	<tr>
		<th width="80"><spring:message code="EmployeeID"/></th>
		<th width="120"><spring:message code="FirstName"/></th>
		<th width="120"><spring:message code="LastName"/></th>
		<th width="120"><spring:message code="Age"/></th>
		<th width="120"><spring:message code="Education"/></th>
		<th width="120"><spring:message code="Salary"/></th>
	</tr>
	<c:forEach items="${employeeList}" var="employee">
		<tr>
			<td>${employee.employeeId}</td>
			<td>${employee.firstName}</td>
			<td>${employee.lastName}</td>
			<td>${employee.age}</td>
			<td>${employee.education}</td>
			<td>${employee.salary}</td>
		</tr>
	</c:forEach>
	</table>
</c:if>
</body>
</html>

Step 16

Create result.jsp

  1.  ${responseMsg}
 ${responseMsg} 


Step 17

Build and deploy the project

Step 18

Let’s Check the output

Access below url to insert the initial sample data

http://localhost:8080/SpringMVCHibernateJNDI/insertSampleEmployees

springmvc_jndi_output1

Access the employees details using below url

http://localhost:8080/SpringMVCHibernateJNDI/employees

springmvc_jndi_output2

Download this project SpringMVCHibernateJNDI.zip

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on