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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
<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>
<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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<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>
<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
2
3
4
5
6
7
8
9
10
11
12
<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"/>
<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
2
3
4
<ResourceLink name="javainsimpleway"
              global="javainsimpleway"
              auth="Container"
              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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
<?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>
<?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
2
<jee:jndi-lookup id="dataSource" jndi-name="java:/comp/env/javainsimpleway"
        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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
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;
    }
}
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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";
    }
}
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
2
3
4
5
6
7
8
9
10
11
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();
 
}
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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();
    }
    
}
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
2
3
4
5
6
7
8
9
10
11
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();
 
}
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
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();
    }
 
}
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<%@ 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>
<%@ 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

Karibasappa G C (KB)
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