This spring hibernate integration tutorial is focused on usage of Hibernate with Spring framework. I will show that how a basic end to end application flow looks like as a result of this integration.
1. Development environment
So if you fall into any of above two category, please read below linked post in case any problem. Spring + Hibernate 4 integration tutorial with all jar files
To build this example project, I will guide you step by step. In this way we able to walk through some concepts also.
2. Create maven web project
Create a maven web project using below command from command prompt.
$ mvn archetype:generate -DgroupId=com.howtodoinjava.app -DartifactId=Spring3HibernateIntegration -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false
Now convert this web project to ecplise dynamic web project using below maven command.
$ cd Spring3HibernateIntegration $ mvn eclipse:eclipse -Dwtpversion=2.0
3. Maven dependecies
Update pom.xml file to include spring and hibernate dependencies. It will also include mysql driver added in project references.
<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>com.howtodoinjava.app</groupId> <artifactId>Spring3HibernateIntegration</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>Spring3HibernateIntegration Maven Webapp</name> <url>http://maven.apache.org</url> <!-- JBoss repository for Hibernate --> <repositories> <repository> <id>JBoss repository</id> <url>http://repository.jboss.org/nexus/content/groups/public/</url> </repository> </repositories> <properties> <org.springframework.version>3.0.5.RELEASE</org.springframework.version> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.15</version> <scope>runtime</scope> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>3.6.3.Final</version> </dependency> <dependency> <groupId>javassist</groupId> <artifactId>javassist</artifactId> <version>3.12.1.GA</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> <scope>runtime</scope> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> <scope>runtime</scope> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.9</version> </dependency> </dependencies> <build> <finalName>Spring3HibernateIntegration</finalName> </build> </project>
4. Create database schema
Now lets decide out database schema structure because it will be needed when we will write the entity classes in next step.
CREATE TABLE EMPLOYEE ( ID INT PRIMARY KEY AUTO_INCREMENT, FIRSTNAME VARCHAR(30), LASTNAME VARCHAR(30), TELEPHONE VARCHAR(15), EMAIL VARCHAR(30), CREATED TIMESTAMP DEFAULT NOW() );
5. Write hibernate entity classes
Now its time to write EmployeeEntity
. This class will be mapped to Employee
table in database using hibernate. JPA will include any class annotated with @Entity
in the persistence management setup. You don’t need persistence.xml
if you use annotations.
package com.howtodoinjava.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="EMPLOYEE") public class EmployeeEntity { @Id @Column(name="ID") @GeneratedValue private Integer id; @Column(name="FIRSTNAME") private String firstname; @Column(name="LASTNAME") private String lastname; @Column(name="EMAIL") private String email; @Column(name="TELEPHONE") private String telephone; //Setters and getters }
6. Write data access code
Lets write our DAO classes which will be responsible for database interaction. This class will be essentially using the hibernate session factory for database interaction. The session factory implementation will be injected into reference variable at runtime using spring IoC feature.
package com.howtodoinjava.dao; import java.util.List; import com.howtodoinjava.entity.EmployeeEntity; public interface EmployeeDAO { public void addEmployee(EmployeeEntity employee); public List<EmployeeEntity> getAllEmployees(); public void deleteEmployee(Integer employeeId); }
package com.howtodoinjava.dao; import java.util.List; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.howtodoinjava.entity.EmployeeEntity; @Repository public class EmployeeDaoImpl implements EmployeeDAO { @Autowired private SessionFactory sessionFactory; @Override public void addEmployee(EmployeeEntity employee) { this.sessionFactory.getCurrentSession().save(employee); } @SuppressWarnings("unchecked") @Override public List<EmployeeEntity> getAllEmployees() { return this.sessionFactory.getCurrentSession().createQuery("from EmployeeEntity").list(); } @Override public void deleteEmployee(Integer employeeId) { EmployeeEntity employee = (EmployeeEntity) sessionFactory.getCurrentSession().load( EmployeeEntity.class, employeeId); if (null != employee) { this.sessionFactory.getCurrentSession().delete(employee); } } }
I have written a manager layer also which seems redundant in this demo due less complexity but it as always considered best practice if you write this. This layer will simply take call from controller and pass this call to dao layer.
package com.howtodoinjava.service; import java.util.List; import com.howtodoinjava.entity.EmployeeEntity; public interface EmployeeManager { public void addEmployee(EmployeeEntity employee); public List<EmployeeEntity> getAllEmployees(); public void deleteEmployee(Integer employeeId); }
package com.howtodoinjava.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.howtodoinjava.dao.EmployeeDAO; import com.howtodoinjava.entity.EmployeeEntity; @Service public class EmployeeManagerImpl implements EmployeeManager { @Autowired private EmployeeDAO employeeDAO; @Override @Transactional public void addEmployee(EmployeeEntity employee) { employeeDAO.addEmployee(employee); } @Override @Transactional public List<EmployeeEntity> getAllEmployees() { return employeeDAO.getAllEmployees(); } @Override @Transactional public void deleteEmployee(Integer employeeId) { employeeDAO.deleteEmployee(employeeId); } public void setEmployeeDAO(EmployeeDAO employeeDAO) { this.employeeDAO = employeeDAO; } }
7. Spring controller and view files
Now its time to write the spring controller and handler methods which will actually be called from spring framework’s dispatcher servlet to process actual application logic.
package com.howtodoinjava.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import com.howtodoinjava.entity.EmployeeEntity; import com.howtodoinjava.service.EmployeeManager; @Controller public class EditEmployeeController { @Autowired private EmployeeManager employeeManager; @RequestMapping(value = "/", method = RequestMethod.GET) public String listEmployees(ModelMap map) { map.addAttribute("employee", new EmployeeEntity()); map.addAttribute("employeeList", employeeManager.getAllEmployees()); return "editEmployeeList"; } @RequestMapping(value = "/add", method = RequestMethod.POST) public String addEmployee(@ModelAttribute(value="employee") EmployeeEntity employee, BindingResult result) { employeeManager.addEmployee(employee); return "redirect:/"; } @RequestMapping("/delete/{employeeId}") public String deleteEmplyee(@PathVariable("employeeId") Integer employeeId) { employeeManager.deleteEmployee(employeeId); return "redirect:/"; } public void setEmployeeManager(EmployeeManager employeeManager) { this.employeeManager = employeeManager; } }
Now we will write our application’s view layer which is actually a .jsp file.
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%> <%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <html> <head> <title>Spring 3 hibernate integration example on www.howtodoinjava.com</title> </head> <body> <h2>Employee Management Screen : Spring 3 hibernate integration example on www.howtodoinjava.com</h2> <form:form method="post" action="add" commandName="employee"> <table> <tr> <td><form:label path="firstname"><spring:message code="label.firstname"/></form:label></td> <td><form:input path="firstname" /></td> </tr> <tr> <td><form:label path="lastname"><spring:message code="label.lastname"/></form:label></td> <td><form:input path="lastname" /></td> </tr> <tr> <td><form:label path="email"><spring:message code="label.email"/></form:label></td> <td><form:input path="email" /></td> </tr> <tr> <td><form:label path="telephone"><spring:message code="label.telephone"/></form:label></td> <td><form:input path="telephone" /></td> </tr> <tr> <td colspan="2"> <input type="submit" value="<spring:message code="label.add"/>"/> </td> </tr> </table> </form:form> <h3>Employees</h3> <c:if test="${!empty employeeList}"> <table class="data"> <tr> <th>Name</th> <th>Email</th> <th>Telephone</th> <th>Action</th> </tr> <c:forEach items="${employeeList}" var="emp"> <tr> <td>${emp.lastname}, ${emp.firstname} </td> <td>${emp.email}</td> <td>${emp.telephone}</td> <td>delete</td> </tr> </c:forEach> </table> </c:if> </body> </html>
8. Spring dispatcher servlet
Our java code is complete and now its time to configure the application. Lets start from web.xml
. In web.xml
, we will configure the front controller for spring framework that is DispatcherServlet.
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee https://www.oracle.com/java/technologies/; id="WebApp_ID" version="2.5"> <display-name>Archetype Created Web Application</display-name> <welcome-file-list> <welcome-file>/WEB-INF/index.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>employee</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>employee</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/employee-servlet.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> </web-app>
9. Spring hibernate integration configuration
Lets configure spring framework for hibernate data source, message resources, view resolvers and other such things.
<?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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop/ http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context/ http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/jee/ http://www.springframework.org/schema/jee/spring-jee.xsd http://www.springframework.org/schema/lang/ http://www.springframework.org/schema/lang/spring-lang.xsd http://www.springframework.org/schema/tx/ http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/util/ http://www.springframework.org/schema/util/spring-util.xsd"> <context:annotation-config /> <context:component-scan base-package="com.howtodoinjava.controller" /> <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property> <property name="prefix" value="/WEB-INF/view/"></property> <property name="suffix" value=".jsp"></property> </bean> <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <property name="basename" value="classpath:messages"></property> <property name="defaultEncoding" value="UTF-8"></property> </bean> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" p:location="/WEB-INF/jdbc.properties"></bean> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.databaseurl}" p:username="${jdbc.username}" p:password="${jdbc.password}"></bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="configLocation"> <value>classpath:hibernate.cfg.xml</value> </property> <property name="configurationClass"> <value>org.hibernate.cfg.AnnotationConfiguration</value> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">${jdbc.dialect}</prop> <prop key="hibernate.show_sql">true</prop> </props> </property> </bean> <bean id="employeeDAO" class="com.howtodoinjava.dao.EmployeeDaoImpl"></bean> <bean id="employeeManager" class="com.howtodoinjava.service.EmployeeManagerImpl"></bean> <tx:annotation-driven /> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> </beans>
Hibernate configuration becomes simple when using annotation.
<?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <mapping class="com.howtodoinjava.entity.EmployeeEntity"></mapping> </session-factory> </hibernate-configuration>
10. JDBC Properties
Lets mention jdbc connection properties and message resource properties.
jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.dialect=org.hibernate.dialect.MySQLDialect jdbc.databaseurl=jdbc:mysql://127.0.0.1:3306/test jdbc.username=root jdbc.password=password
That’s it. Your application is ready to be deployed on server of your choice. At the end, your project structure should look like this.

If you find any issue in building or running this spring hibernate integration example in eclipse step by step, drop em a comment and I will try to help you.
Update:
Possible Solution: Please try changing org.springframework.orm.hibernate3.LocalSessionFactoryBean to org.springframework.orm.hibernate4.LocalSessionFactoryBean
===hibernate3 to hibernate4===
More references:
https://stackoverflow.com/questions/7528862/exception-noclassdeffounderror-for-cacheprovider
https://code.google.com/archive/p/jgk-spring-recipes/wikis/Migrating_Spring31_Hibernate4.wiki
java.lang.NoClassDefFoundError: org/aopalliance/intercept/MethodInterceptor
Possible Solution: Download and add com.springsource.org.aopalliance-1.0.0.jar to your classpath
Refer:
https://spring.io/blog/2019/02/06/legacy-forums-will-be-shutdown-february-28
Happy Learning !!
Saurabh Chopra
Hi Lokesh,
I created a method with @Transactional annotation in a class and called that method in the same class without any object reference ..it is not creating any transaction. how i should be handling it.
Shahrukh
Thanks a lot man! It works.
God Bless you
le-seigneur
hi,
looking the network traffic with firefox development tools (F12) i’m surprised to find the password in clear in the param of the POST request:
j_username: demo
j_password: 1234
Thanks
Dilini
I’m getting given errors in employee-servlet.xml
Please help.
omarghazala
remove / at the end of every xsi:schemaLocation: “url”
arun singh
Thanks sir
saravanan
cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element ‘context:annotation-config’.
TomSkyer
remove / at the end of every xsi:schemaLocation: “url”
OSMAN
hello,
i need a JPA exemple to improve my quality
the Spring hibernate exemple is a good exemple for me that i thnak you
best regards
Selven
Hi,
I am facing this error when I run spring and hibernate integration in eclipse:
Lokesh Gupta
Check for namespace declaration. xmlns=”http://www.springframework.org/schema/beans
xsi:schemaLocation=”http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
m
hi, could you show an example of integrating jsf, spring and hibernate? Thank you
Lokesh Gupta
Added in my TODO list.
Davis
Hi Lokesh,
I created a project in Eclipse Luna. I picked jboss-javaee6-webapp-ear-archtype. I dropped the sample code in the respective folders.Project builds with out errors. But I am getting following errors.
Initialization of bean failed; nested exception is java.lang.ClassCastException: org.springframework.transaction.annotation.Propagation cannot be cast to org.springframework.transaction.annotation.Propagation
Lokesh Gupta
Never heard of this error. I will try to find a solution for it. As of now, I have no clue.
Davis
Is there any way I can send a screen shot of my project structure ?
My best guess is, it is due to following keywords in spring-servlet.xml.
Lokesh Gupta
Send me at howtodoinjava@gmail.com
Davis Alengaden
Hi Lokesh,
I could fix the issue. As I had picked jboss-javaee6-webapp-ear-archtype ,
there were three projects in the project structure – ear, ejb and war. Each project has its own porm and one main porm. I had same porm entries in multiple pom.xml which caused the issue. I removed redundant entries and dropped your project in appropriate folders in sync with archtype…. everything works fine now.
Thank you
Davis
ss..
Hi i am not able to import this project..
shweta
Getting exception in spring maven project–Servlet /Emp threw load() exception.
I have added all the dependencies in pom.xml.
rohit
getting this exception when running the application on jboss 7.1.
Amarjeet kumar
Hi Lokesh….
I have go through this code ….it is very easy to Understand the concept of Spring Hibernate Integration But….when I choose add maven project option and i have seen in my Project Explorer ….Some error like:—
“The superclass “javax.servlet.http.HttpServlet” was not found on the Java Build Path”
Danish
Project->Properties->Target Runtimes->Apache Tomcat
Tsuisou
I have this problem when I try to run the project. SB help me?
HTTP Status 500 – javax.servlet.ServletException: javax.servlet.jsp.JspTagException: No message found under code ‘label.firstname’ for locale ‘pl’.
type Exception report
note The full stack trace of the root cause is available in the Apache Tomcat/8.0.20 logs.
Apache Tomcat/8.0.20
Lokesh Gupta
Create a file messages_pl.properties with content of messages_en.properties (you can translate the values as well) in resources folder.
Ricardo
Hello!
How could I make a simple and efficient way to handle exceptions returned from my oracle database through the spring? Would use the DataAccessException? Thank you!!
Lokesh Gupta
Personally, I am not big fan of DataAccessException. I usually like to have more control over exceptions using @ExceptionHandler approach.
If you are looking to translate oracle exception codes directly then YES, DataAccessException is good way. If you are more concerned about handling exceptions, then try second approach.
Ricardo
I am not able to intercept the exception. He goes straight. Already put in catch ConstraintViolationException, Exception and DataAccessException but does not work. Would have any examples of how you did?
Following error:
Lokesh Gupta
This thread will help you if you not gone through it already. TODO: Catch the exception outside transaction boundary. This exception is not thrown by spring managed bean. Rather hibernate’s transactionmanager is throwing it from some proxy object.
Badal
Getting below error. Please help!!!
Lokesh Gupta
Please use latest spring jars; and remove any older versions if any.
Iniya
I tried both your below examples. Both are opening white blank page in the browser. Log files in tomcat is given below. I have been working on this for few days now. Please help me.
https://howtodoinjava.com/spring-orm/spring-hibernate-integration-example/
https://howtodoinjava.com/struts2/spring-4-struts-2-hibernate-integration-tutorial/
http://localhost:8081/Spring3HibernateIntegration/index.jsp
http://localhost:8081/Spring3HibernateIntegration/editEmployeeList.jsp
http://localhost:8081/Spring3HibernateIntegration/
localhost_access_log.2014-12-18.txt
0:0:0:0:0:0:0:1 – – [18/Dec/2014:12:00:46 -0500] “GET /Spring3HibernateIntegration/ HTTP/1.1” 404 –
0:0:0:0:0:0:0:1 – – [18/Dec/2014:12:01:51 -0500] “GET /Spring3HibernateIntegration/editEmployeeList.jsp HTTP/1.1” 404 –
0:0:0:0:0:0:0:1 – – [18/Dec/2014:12:01:55 -0500] “GET /Spring3HibernateIntegration/editEmployeeList.jsp HTTP/1.1” 404 –
0:0:0:0:0:0:0:1 – – [18/Dec/2014:12:01:56 -0500] “GET /Spring3HibernateIntegration/editEmployeeList.jsp HTTP/1.1” 404 –
0:0:0:0:0:0:0:1 – – [18/Dec/2014:12:01:57 -0500] “GET /Spring3HibernateIntegration/editEmployeeList.jsp HTTP/1.1” 404 –
0:0:0:0:0:0:0:1 – – [18/Dec/2014:12:06:11 -0500] “GET /Spring3HibernateIntegration/ HTTP/1.1” 404 –
Lokesh Gupta
“GET /Spring3HibernateIntegration/ HTTP/1.1″ 404
Something bad happened during deployment i.e. startup time in tomcat. Please check server logs. Are there any error while startup?
prem
Consider there are multiple requests. Since same instance of the servlet runs and Spring bean (EmployeeManager) isnot thread safe..How Spring bean thread-safety is taken care.
@Autowired
private EmployeeManager employeeManager;
Lokesh Gupta
Above variable (and other similar data as well) is not stateful data. Except initialization, no thread will ever change/modify it. Usually Manager and DAO layer classes never store any stateful data which is changed by any thread. And until you have any stateful data which can possibly be corrupted, never worry about multi-threading issue.
prem
Thanks, got it now.
Umashankar
SEVERE: Context initialization failed
Hi,
I am getting above error while trying to run the application in eclipse. Have added all necessary jars.
Please help where i am going wrong in this..
Lokesh Gupta
“java.lang.NoClassDefFoundError: ch/qos/logback/core/joran/spi/JoranException” says all. Logback dependency is missing..
vinayak
Check once your .jar file in the WEB-INF/lib foloder..
Abhijeet
HI Lokesh very nice explanation and helpful though.
I have question: when you return a list of Employee Entity you are returning it from singleton employeeManager as you are not Specifying any scope to it, but while the list changes how does it ensure that the singleton returns the new list every time a a request is made as singleton objects only constructed once .
Thanks in advance !!!
Lokesh Gupta
Singleton pattern should only be concern when object is stateful. Stateless objects do not need to be singleton in applications (usually). You will read good information here: https://howtodoinjava.com/tomcat/a-birds-eye-view-on-how-web-servers-work/
Abhijeet
Hi Lokesh, I meant to say what if the Employee Entity returns a Prototype Bean what if the list changes frequently. and how that would be handled if its constructed as Signleton Bean
Lokesh Gupta
EmployeeEntity as well as list of entities, is created always by hibernate and totally depends on number of rows obtained as result of query executed. Spring does not create either List of entities, or single entity. And Hibernate always create a new instance of list after query execution.
I hope I understood your concern right, this time 🙁 . Please let me know if I am still not able to clear your doubt.
Abhijeet
Yes that answers my question how does it works in case of Springs leave alone the Hibernate just Spring i wanted to know how can be a prototype bean may always give new value when its a dependency in an Singleton Bean … means when you try get a singleton bean when it has a prototype bean added as dependency
Lokesh Gupta
“Lookup Method injection” is there exactly for this purpose. See a good example here: https://prasanthnath.wordpress.com/2013/03/21/injecting-a-prototype-bean-into-a-singleton-bean/
Abhijeet
Thanks Lokesh for all you explanations this is simply amazing and thanks a lot for helping me 🙂
padobPaul
Thank You for great example of integration. It’s one of the best sources of knowledge in this topic as far I’ve found.
Good luck and
manikandan
Hi. i am new for Spring and Hibernate, i can’t able to download relevant jar file on it, ll u pls help me.
Lokesh Gupta
Download from here: https://howtodoinjava.com/spring-orm/spring3-hibernate4-integration-example/
vinay
how can we handle multiple controller in our code ?
Lokesh Gupta
You can have multiple classes annotated with @Controller. Is it something else you are seeking?
JEYASEKAR
where/what i need to change?
Am using java 1.6.
Lokesh Gupta
Don’t know the root cause but adding this to pom.xml should solve the issue.
Doreen
Hi thanks for this tutorial,
i met with this error, you do know whats causing the issue?
HTTP Status 500 – Request processing failed; nested exception is org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Cannot open connection
Lokesh Gupta
Connection can not be opened. Please verify your db credentials.
Doreen
i’ve tried googling about the error, and made changes in the jdbc.properties as well as employee-servlet.xml but it still doesnt works. any idea?
Dinesh
Thanks for your tutorial.
I’m the beginning of spring and hibernate. I want to learn the basic of spring and hibernate. Can you tell me which is a helpful tutorial (Which you are written) or books to learn the spring and hibernate basic concepts?
I only know the core Java concept.
Thanks in Advance.
Srikanth
Hi Lokesh, I’ve tried your code,but getting that Entity class given in mapping tag of hibernate.cfg.xml is not loading …causes hibernate mapping exception…. .might be am in wrong way…could you please help me out… thanks in advance…
Ambet
Thank you Mr. Lokesh, Nice blog for beginners! I was just wondering what do you use in wordpress to post the code blocks?
Lokesh Gupta
Plugin name is SyntaxHighlighter Evolved
Venky
Good job Mr. Lokesh, Also please post one sample application on Struts 1.x, Spring and Hibernate Integration in real time level.
Lokesh Gupta
May be it will help you. It is using struts 2 in tutorial, but you can easily replace the pieces from specific to struts 2 to struts 1.
https://howtodoinjava.com/struts2/spring-4-struts-2-hibernate-integration-tutorial/
Venky
Thanks for your post, Mr Lokesh, I will let you know if i need any clarifications.
Aina G
Hi Mr Lokesh, thank you for your tutorial it helps me to understand Maven
But i have error when i compile; i used your code 100% without changed anything
I use netbeans not Eclipse and i have this error
[/java]
Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘editEmployeeController’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.howtodoinjava.service.EmployeeManager com.howtodoinjava.controller.EditEmployeeController.employeeManager; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ’employeeManager’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.howtodoinjava.dao.EmployeeDAO com.howtodoinjava.service.EmployeeManagerImpl.employeeDAO; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ’employeeDAO’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory com.howtodoinjava.dao.EmployeeDaoImpl.sessionFactory; nested exception is java.lang.NoClassDefFoundError: Lorg/hibernate/cache/CacheProvider;[/java]
Best regards
Aina
Lokesh Gupta
Have you tried the solution I suggested in last of post in first red block.
If you are facing issue :: “java.lang.NoClassDefFoundError: Lorg/hibernate/cache/CacheProvider”
Possible Solution: Please try changing org.springframework.orm.hibernate3.LocalSessionFactoryBean to org.springframework.orm.hibernate4.LocalSessionFactoryBean
Aina G
Hi Mr Lokesh,
Thank you for responding so quickly, i did it and i have two errors:
First error is :
can you give me your e-mail? I would like to improve my knowledge in java and I need help to make it happen1!
Best regards
Aina G
Aina G
Hi, Mr Lokesh, I did as you said to me, the error disappears but an another appears.
This is the error:
Invalid property ‘sessionFactory’ of bean class [org.springframework.orm.hibernate4.LocalSessionFactoryBean]: Bean property ‘sessionFactory’ is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
Can i have your e-mail, I would like to improve my knowledge in java and I need help to make it happen.!!
Best regards,
Aina G
amarnath
First of all Thanks for the wonderful tutorial. I have successfully integrated Hibernate with Spring following your tutorial.
But I have one problem, I have included one more DTO that is UserDTO and mapped to USER table in my MYSQL and I have included it in the hibernate.cfg.xml file like below,
The problem is, it is working fine for the FeedbackDTO but for the UserDTO I am getting an exception as below,
HouseController:64 – ERROR: HouseController.verifyCredentials USER is not mapped [FROM USER]
I am unable to figure out, so please let me know how can I solve this.
Lokesh Gupta
Looks like posted code was lost. Please post the code in tags as suggested above comment box.
amarnath
I am able to solve it .. I made a mistake in the Query.
Query query = session.createQuery(“FROM User”); // Here I am using Db-table name instead of that I have to use the DTO name which I have mapped with the DB-Table;
Query query = session.createQuery(“FROM UserDTO”);
Lokesh Gupta
This is the best thing happened. I really like when somebody solves his problem in his own way.
ravi
hi lokesh
am getting
org.apache.jasper.JasperException: javax.servlet.ServletException: java.lang.StackOverflowError
this error and am not using maven dependency
solution
….
Lokesh Gupta
It may happen if your hibernate entities refer to each other such that they create a loop. Check for relationships between hibernate entities.
Wilfredo G.
Hi Lokesh, How can I get contact with you. I have a project that I need some help with. It is a Spring Hibernate project.
Thanks
Wilfredo
Lokesh Gupta
Howtodoinjava@gmail.com
Lilliana
Hi, i did the first steps but when i imported the project i received this error:
Faceted Project Problem (Java Version Mismatch)
How i can do to solve this problem?
Lokesh Gupta
Define the minimum and max JDK version in last of pom.xml like this.
anil
hi Lokesh, need to know few things i want project structure in maven like src/main/java, src/test/java, src/test/resources which archtype i need to use? give me the detailed explanation how to create this type of project structure
Lokesh Gupta
You should be using maven-archetype-webapp or maven-archetype-quickstart, depends on nature of java project i.e. webapp or normal java app.
More info is listed here:
https://maven.apache.org/archetypes/maven-archetype-quickstart/
https://maven.apache.org/plugins-archives/maven-archetype-plugin-1.0-alpha-7/examples/webapp.html
ravindhar
Hi lokesh actually the spring with hibernate directory structure is zig zag i will more elaborate means that musch of complexity having not understand easily understanding
Lokesh Gupta
Having hard time in understanding the comment.. 🙁
anil
did it by integrating with maven-plugin lokesh….can u post the same example by using Jquery…i want to know how it can be integrated….
Binh Tran
Hi Lockesh,
Would it be best if we don’t mix Spring DI with Hibernate in DAO layer? so we can have total separation between Data and Service Layers?.
1. Remove Hibernate related Configuration from Spring Bean and put them on backend Data layer
2. Only Use EmployeeDAO in Spring Bean configuration and AutoWire to EmployeeManager (service layer)
Please Advice.
Thanks Binh.
Lokesh Gupta
Hi Binh, Can you please elaborate more on “Remove Hibernate related Configuration from Spring Bean and put them on backend Data layer”? What exactly you want to do and it’s benefits?
Binh Tran
Hi Lokesh,
What I meant is to decouple Hibernate from Spring. The benefit is to remove coupling and having separation of layers. Please let me know if it is a good idea?
Thanks.
Lokesh Gupta
Decoupling in any form is always welcome in my view. Here I really have to think hard of a good way to decouple hibernate from spring completely. I will do my research. If you got any good suggestion, the please share it with all.
prem
Hi lokesh,nice Example..but how to do validations for the fields i.e when they don’t enter any fields.
riya
Hi Lokesh, I have few queries in integration of spring and hibernate. I need your email id. Please reply back to this message.
Sandeep
Hi Lokesh, i got good knowledge ..it is very useful for me…. one more thing instead of using sessionFactory we can use Hibernate Template class… we can reduce the code.. i think so no need of separate hibernate configuration file.. we can directly injected to AnnotatedSessionFactory ..
Lokesh Gupta
Good Points. May be I should write another post with above suggestions.
bernard
Thank-you so much for the work done
Mohan
Hi Lokesh,
index.jsp (welcomefile) is not calling here.could you clarify it?why is it ignoring here?
Surendra
public List getAllEmployees() {
return this.sessionFactory.getCurrentSession().createQuery(“from EmployeeEntity”).list();
}
EmployeeEntity created well and used for , but there is compile time error say “EmployeeEntity” can’t resolved the symbol….
see also in stackoverflow https://stackoverflow.com/questions/22606636/spring-hibernate-sql-entity-name-not-resolved
Surendra
Sorry that was behavior of Intellij IDE…after adding hibernate support for the project…that error resolved…Thank you!!! your project successfully run…
Lokesh Gupta
Glad, you resolved it.
Vipin
public List getAllEmployees() {
return this.sessionFactory.getCurrentSession().createQuery(“from EmployeeEntity”).list();
}
this is not working for me ….
i had almost copied yours example….
Lokesh Gupta
What’s the problem you are facing. Any exception?
Lokesh Gupta
Use below code:
ApplicationContext ac = new ClassPathXmlApplicationContext(“net/core/example/app-context.xml”);
In maven src/main/java is directory structure and not included in class path. From next time, confirm the path in “classes” folber inside “target” folder.
Vipin
Hi Lokesh….
i m new to hibernate n facing a problem ….which is how to retrieved a single object from a database…
and also a list of objects from database…..
whenever i tried to retrieved a single employee object ..error is…. get or load is not valid without active transaction… i had gooogled a lot but unable to fix this problem…Also
Can we return a object after retrieving it in service layer from try n catch block..???
Lokesh Gupta
Can you please post your hibernate configuration code and code where you are getting this exception. First look suggest that you are opening the transaction after a get/load method call. I.e. load() method is called outside a transaction.
harish
Dear Sir,
I am getting java.lang.AbstractMethodError: javax.servlet.jsp.PageContext.getELContext()Ljavax/el/ELContext; error while deleting with the ID.
Praveen
Thanks for providing working model to get started with.
ganesh
i am getting following exception:-
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name ’employee’ available as request attribute
raja
try it one more time
Binh Thanh Nguyen
Thanks, nice post.
Prashanth
what are the jar files i need ti include in lib directory if i build the project from source without using maven..
Lokesh Gupta
You can refer here: https://howtodoinjava.com/spring-orm/spring3-hibernate4-integration-example/
Siva
Hi Lokesh,
It’s really good sample to start with Spring and hibernate framework. I’m trying to follow the steps you have described, but i’m getting below warning message while executing the command “mvn eclipse:eclipse -Dwtpversion=2.0” at step 2:
[WARNING] Workspace defines a VM that does not contain a valid jre/lib/rt.jar: C:\Program Files\Java\jre7
What could be the reason for this warning message. Could you please assist me to over come this?
Thanks,
Siva
Vijay
Hi Lokesh! This article was very helpful.Thank you so much!!!!!!! Day by day I am becoming your fan!!!!!!
Manisha Pandey
Hello wanna thank you for this amazing tutorial ….I ws successful in this but when I tried this with JSF instead of JSP i am getting exception
It will be realy kind of you if u culd help me with this and explain the same thing with JSF. Thank you again
Lokesh Gupta
Just make sure you got spring web module loaded in runtime:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${org.springframework.version}</version>
</dependency>
kalyan
really useful …thank u so much 🙂
Piyush Grover
Thanks Lokesh sir. Awesome post.
Andrew
Sad to say but this tutorial is so messy and waste of time. Missing lots of instructions, I set up totally fresh envirnoment and it generated me lots of erros. Right after importing fresh maven generated files into Eclipse. I do not want to point all the missing things because there is a lot of them but for example author doesnt says how to import project into Eclipse (this step already generated number of errors) Than creation of Java class and its’ location is not mentioned. For me it was just lost of time going through this mess. I would suggest author to test his tutorials on fresh envirnoment not on half configured, that would saved a log of time his readers. I went through few of Lynda.com tutorials and NEVER have any suprising error.
Lokesh Gupta
I am very sorry if this tutorial caused so much pain to you. But, believe me I got lots of positive feedback for this tutorial and many people configured it in their first attempt.
Though, I do not expect anybody to configure all above steps in first attempt because they are complex for many of us. But, even if you are able to execute it in an hour also with 4-5 problems, then also I would say it’s good for you. I call this learning by mistakes. It is much more important than able to execute the project in first attempt.
Just to mention, I have attached the whole sourcecode (which is 100% correctly configured and executable) for reference if somebody struck for long time.
velmurugan
Hi Lokesh,
I am getting below error.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘sessionFactory’ defined in ServletContext resource [/WEB-INF/employee-servlet.xml]: Invocation of init method failed; nested exception is org.hibernate.MappingException: Unable to load class [ com.howtodoinjava.entity.EmployeeEntity] declared in Hibernate configuration entry
.
.
.
Caused by: org.hibernate.MappingException: Unable to load class [ com.howtodoinjava.entity.EmployeeEntity] declared in Hibernate configuration entry
at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:2126)
Please suggest me, what i need to change the code.
Lokesh Gupta
Please make you have .class file generated in required pacakge. com/howtodoinjava/entity/EmployeeEntity
Roushan
thanks Sir u r doing a very helpful work.
Venkata Sriram
Hi sir.i used the same code to delete an employee,but in my case iam having extenstion in web.xml as *.vja so when i use delete it is not going to controller sir. in controller also same code i followed as explained in the tutorial.please Help me sir.
Thanks
Venkata Sriram
Venkata Sriram
Hi sir please help me sir.
Lokesh Gupta
Can you please zip the source code and upload to google docs and send me link. If zipped folder is small, send it directly to my mail id. howtodoinjava@gmail.com
sarojineveen
i am facing this error can you please help me.
WARNING: No mapping found for HTTP request with URI [/SpringwithORM/] in DispatcherServlet with name ’employee’
Jan 17, 2014 4:11:52 PM org.springframework.web.servlet.DispatcherServlet noHandlerFound
nadhine
hello! thanks for the tutorial. I would like to know one thing … within your project has other things … login, logout, access denied, but the project goes only to “Employee Management” screen is ok? Or missing something here? If not how can I implement this elsewhere?
Sorry for my english GTranslate
Lokesh Gupta
It’s how it has been written. If you want to forward any other screen you can do so.
Mike
Lokesh,
I followed your tutorial and used the same design except I wanted to use Volleyball recruits instead of Employees so I had…
Volleyball (instead of Spring3HibernateIntegration)
Recruit (instead of EmployeeEntity)
RecruitDAO (instead of EmployeeDAO)
RecruitDAOImpl (instead of EmployeeDAOImpl)
so forth and so on….and I changed all the references accordingly in all the files.
Also, I am using Tomcat instead of JBoss.
However I keep getting this error when I try to launch the program inside of STS. (Yes I’m also using Spring Tool Suite).
Jan 06, 2014 9:48:13 AM org.springframework.web.servlet.DispatcherServlet noHandlerFound
WARNING: No mapping found for HTTP request with URI [/volleyball/] in DispatcherServlet with name ‘recruit’
I will gladly post the code if you request so.
Thanks and thanks for the excellent tutorial.
Mike
Lokesh Gupta
When you start the tomcat, you will see the server logs in console like below:
Jan 7, 2014 12:41:07 AM org.springframework.web.servlet.handler.AbstractUrlHandlerMapping registerHandler
INFO: Root mapping to handler 'editEmployeeController'
Jan 7, 2014 12:41:07 AM org.springframework.web.servlet.handler.AbstractUrlHandlerMapping registerHandler
INFO: Mapped URL path [/add] onto handler 'editEmployeeController'
Jan 7, 2014 12:41:07 AM org.springframework.web.servlet.handler.AbstractUrlHandlerMapping registerHandler
INFO: Mapped URL path [/add.*] onto handler 'editEmployeeController'
Jan 7, 2014 12:41:07 AM org.springframework.web.servlet.handler.AbstractUrlHandlerMapping registerHandler
INFO: Mapped URL path [/add/] onto handler 'editEmployeeController'
Jan 7, 2014 12:41:07 AM org.springframework.web.servlet.handler.AbstractUrlHandlerMapping registerHandler
INFO: Mapped URL path [/delete/{employeeId}] onto handler 'editEmployeeController'
Jan 7, 2014 12:41:07 AM org.springframework.web.servlet.handler.AbstractUrlHandlerMapping registerHandler
INFO: Mapped URL path [/delete/{employeeId}.*] onto handler 'editEmployeeController'
Jan 7, 2014 12:41:07 AM org.springframework.web.servlet.handler.AbstractUrlHandlerMapping registerHandler
INFO: Mapped URL path [/delete/{employeeId}/] onto handler 'editEmployeeController'
See if your URL is scanned and registered.
Mike
Lokesh,
Here is the text from the console. I don’t think the SLF4J error is the problem and I think the URL (http://localhost:8080/volleyball) is registered but I’m not certain.
Lokesh Gupta
If it is small project, can you please ip the source and upload it go google docs. And send me link on howtodoinjava@gmail.com
Mike
Lokesh,
Check your email.
Thanks
Mike
Lokesh Gupta
Got your email. I will reply you on sunday coz I am on vacations and with limited resources here.
Mike
Lokesh,
Enjoy your Vacation. This can wait.
Mike 🙂
Lokesh Gupta
Finally I looked on this application. I didn’t find any problem with code. I believe problem is with program structure because when I used the same code and dependency in separate project, code worked fine. Below are steps I followed:
1) Create new maven project: [I renamed the project to vollyballs]
D:Latest Setupeclipse_juno_workspacevollyballs>mvn archetype:generate -DgroupId=com.howtodoinjava -DartifactId=vollyballs
-DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false
2) Concert to eclipse supported project
cd vollyballs
mvn eclipse:clean eclipse:eclipse -Dwtpversion=2.0
3) Import project into eclipse and copy files from your code
4) Execute command:
mvn eclipse:clean eclipse:eclipse -Dwtpversion=2.0
to update dependencies5) Deploy the app in tomcat server. Application was good and running.
I have uploaded the working code here:
https://drive.google.com/file/d/0B7yo2HclmjI4YTlVUkpSZ1YwS1k/edit?usp=sharing
Venkata Sriram
Hi sir, iam newbie to spring.Iam having a doubt related to beans sir.i read your tutorial regarding Autowired and it types.and practiced the spring hibernate integration example.
i want to call a method in the same bean then how i have to call sir.
like
public class XX
{
public String AA()
{
//Here i want to call BB() with out using new method is it possible sir ?
}
public String BB()
{
}
}
public class YY
{
@Autowired
private XX x;
then
x.AA();// will work sir
x.BB();//working
}
but in the same bean how to call iam confusing please help me sir
Lokesh Gupta
Not sure what exactly you are looking for? Which method call you want to make in which class in your code sample?
Venkata Sriram
Hi sir,i want to call method BB() from AA() sir.
Lokesh Gupta
For calling methods defined in same class, you don’t need to do anything. Basic java rule. Call it directly. OR I am not getting you properly?
Venkata Sriram
ok sir .Thanks for clarification sir.
rajeshboy44
Hi lokesh, could you help me regarding how to manage transaction in spring with hibernate, i used annonation @transactional on service method. but i want to use manually
Session session = sessionFactory.getCurrentSession();
TransactionManager tx = null;
try {
tx= session.beginTransaction();
…..
..
..
tx.commit();
} catch (Exception e) {
tx.rollback();
}
but it doesn’t working.
so please tell me how to use?
your site is good but how to post new thread or blog here..
thanks
Lokesh Gupta
What’s problem you are facing in above code? AND, I will recommend you to use annotations for controlling transactions. It is more manageable and reduce lots of code. I am planning to add a forum in this blog, so that problems like this can be discussed in detail there.
Dilip
Its working fine , gr8 .. test .Thanks
amit
good work you have done man.
Thanks alot!!!
Sebastian
Hello, can you help with this error?
Lokesh Gupta
Spring web is not included in dependencies.
Sebastian
Can you tell me how to do that? I’ve just started studying this. I must mention that I use STS(Spring Tools Suite) and I created a Dynamic Web Project from the beginning. Thank you.
helios
Could you please help me a problem.
When i start Tomcat, occur an error. Although, I used the springweb jar in the library.
helios
Thanks, I solved this problem.
Lokesh Gupta
🙂
Ola
how to solved this problem?
Andros
Hello!!
I have this problem. when I run the example it appears in my web browser a 404.in both jsp (index and edit…)
the web project its exactly as yours. This is the jars that I have in the lib
com.springsource.org.aopalliance-1.0.0.jar
commons-dbcp-1.4.jar
commons-logging.jar
hibernate-core-3.6.3.Final.jar
jstl-1.2.jar
mysql-connector-java-5.1.27.jar
org.springframework.web.servlet-3.0.0.M3.jar
spring-aop-3.0.3.RELEASE.jar
spring-asm-3.0.3.RELEASE.jar
spring-beans-3.0.3.RELEASE.jar
spring-context-3.0.3.RELEASE.jar
spring-core-3.0.3.RELEASE.jar
spring-expression-3.0.3.RELEASE.jar
spring-tx-3.0.3.RELEASE.jar
spring-web-3.0.3.RELEASE.jar
spring-webmvc-3.0.3.RELEASE.jar
And I really need your help here. I know that the problem is in the web.xml but where???
thanks
Lokesh Gupta
Any problem seen in server logs?
Alex
I have the same problem, the same jars and in the server logs. are in white
nothing
A M Bharath
Hello Lokesh,
A general question regarding the concept of DAO layer…I assume the DAO interface represents a blueprint of various CRUD operations that can be performed on a Datasource (any datasource in fact) and each DAOImpl class refers to a specific Datasource (like MySQLDaoImpl, MongoDBDaoImpl etc) right? If this is the case, how to fit in some operational semantics that vastly differ from one Datasource to the another for the same kind of operation?
Eg:
public Object save(Object obj) -> let us say this applies to an insert operation using Hibernate for a MySQL datasource
public void save(Entity entity) -> let us say this applies to the same operation (insert) using some other JPA-based ORM for a NoSQL-type datasource like Cassandra/MongoDB
Please note that Entity, in the aforementioned, is the JPA-standard Annotation type.
In this case, how do we go about designing the interface and/or implementation classes of the DAO layer?
Sincerely,
A M Bharath
Lokesh Gupta
Bharath, It is a good question. My understanding is that we should not use Entity or any such class extensions out of DAO layer. We should use VO (Value objects) or TEO (Transfer Entity Object) which have almost similar fields/getters,setters/structure as Entity.
These VOs however can be used as model at view layer. And they will be present at controller and service layer, but not at DAO layer.
e.g. public EmployeeVO save(EmployeeVO employee);
Above declaration will completely de-couple the DAO layer from service layer because it does not care what you do in DAOImpl with EmployeeVO object, It just want that employee information saved somehow. Similarly other DAO methods will not accept/return any entity type thing. They will return only void/common java types or VO objects. They just need to copy the values from VO objects to DB specific objects and use them afterward. Similarily, after fetching data, they need to copy information in VO objects and return it.
In future, if you want to move from from hibernate to MongoDB, you will have to change only DAOImpl classes.
Am I missing anything???
A M Bharath
Perfect! 🙂 I now understand what it means to truly decouple the DAO layer from the others…you cleared my question to the fullest! Thanks!!
Sincerely,
A M Bharath
Akram
Thank you Gupta,
I imported this tutorial in my STS it’s working, did you forget to implement the update ?
Thanks
Ravi Kumar
How to update ? can you share that.?
Lokesh Gupta
Add another method updateEmployee() and it’s code. By the way, it’s not main discussion in post. Post is about integration with Spring 3. I will appreciate If you try first.
Ravi Kumar
If i click on delete it is not deleting that row .In console “Hibernate: select registeren0_.id as id2_, registeren0_.NAME as NAME2_ from RegisterEntity registeren0” my application is same as above.How to solve it ?
Ravi Kumar
I added methods for update and edit also.Two things are done.
Thank you Gupta.
prasanta
santhosh
Hi lokesh,
Please can you guide dwr integration with same application???
thanks in advance..
santhosh
Hi,
for same example can you guide us how to integrate with dwr (ajax)????
Lokesh Gupta
Currently on vacations. I will try.
Dinesh
I am doing small application is same as above,every thing is working but if i click on delete it is not deleting that row .In console “Hibernate: select registeren0_.id as id2_, registeren0_.NAME as NAME2_ from RegisterEntity registeren0_”
..where i did mistake can you help me for this.
Dilli
How to solve this ?
Lokesh Gupta
Paste your hibernate config here.
Tyrone
Hi Lokesh
Please assist, I have downloaded the source code and imported into Eclipse. I’ve made relevant changes to jdbc.properties
I want to do it step by step once I am sure that the project is running on my machine.
When I run the project I get Http status 404 – The requested resource (/Spring3HibernateIntegration/) is not available.
Please help, what am I missing. I’m new to Spring3MVC
Lokesh Gupta
Please ensure you have all .class files and .xml files in target folder (i.e. project is build correctly). If still facing issue, give the error logs in server console.
Ajay Shilwant
Hi,
help me to solve this issue …
Lokesh Gupta
I updated the post just few minutes before. Look at the end (near sourcecode link) for possible solution.
Ajay Shilwant
Lokesh Gupta
https://stackoverflow.com/questions/8565051/spring-3-1-hibernate-4-sessionfactory
https://code.google.com/archive/p/jgk-spring-recipes/wikis/Migrating_Spring31_Hibernate4.wiki
Das Kumar
While doing one application i am getting this error:
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name ‘register’ available as request attribute
..How to solve this error can you help me
Lokesh Gupta
The root caused is the incorrect view name in JSP page.
@RequestMapping(“/customer.htm”)
Das Kumar
not required action ?.I am doing small application same as above application.In the above application you did’t write like .htm in request mapping.May i know what is the exact problem.
Lokesh Gupta
It’s not about extension. They are for example only. Please verify “commandName” property and related things.
Das Kumar
how to edit particular id details..can you please write that code.please help me
Das Kumar
After downloading and extract .To run this project which files are required to paste in eclipse,but not in maveen project.how to do it ?
Lokesh Gupta
Add all required jar files. They are in .classpath file in attached sourcecode.
Das Kumar
Thank you, it is working. I am new to spring MVC,Shall i write 3 or more controllers in one package ?
Lokesh Gupta
If you can logically group them, and group them in package also.
Das Kumar
I want to display id,how to get id from data base .can you please send to my mail.
Lokesh Gupta
You have the id field in entity. You can use that. Is there any other id you are looking for?
Das Kumar
That id only.And one more thing is edit link i have to write there .if i click edit link one small window should come and there i want to edit.if it is possible please share sir.
Sandeep Tyagi
Hi Lokesh,
May you please post your POM file also in this blog, because of security reason i am not able to down load project source code?
Lokesh Gupta
check your email.
Arun Kumar
Hi Lokesh,
Thank you, whenever I am getting confused about any java related concept, I read your concept and always resolve my doubts.
Thank lots.
Bharath
Hi Lokesh,
In the EMPLOYEE table, there is a column, “CREATED TIMESTAMP DEFAULT NOW()” but the EmployeeEntity class doesn’t seem to have a property representing this. Can you please explain how this column is getting updated upon the execution of the addEmployee(…) method?
Also, I’ve seen some posts in StackOverflow where there are recommendations to use JPA annotations like @PrePersist, @PostPersist etc to update TIMESTAMP columns (like CREATED, LAST_UPDATED etc). It has also been mentioned that Hibernate doesn’t support these annotations by default and that some listeners have to be used. Do you have any inputs in this regard?
Lokesh Gupta
I have used “DEFAULT NOW()” in DB schema for table which causes to store current timestamp everytime a new record is added.
@PrePersist, @PostPersist are new to me. I will learn more on them, and share my views.
A M Bharath
Hello Lokesh,
Thanks for your reply – in effect, you wrote the timestamp logic in your DB itself! Good idea there!
I was looking up some information on @PrePersist and @PostPersist etc. These are pure-JPA annotations and can’t be used with Hibernate’s SessionFactory. The work-around is to use either an interceptor https://dzone.com/articles/using-a-hibernate-interceptor-) OR an event-listener http://leakfromjavaheap.blogspot.com/2013/08/prepersist-and-preupdate-not-working.html & https://timezra.blogspot.com/2011/10/jpa-callbacks-with-hibernate.html
Do have a look at these since I’m sure these will make better sense to you than the newbie in me! 🙂
Thanks,
A M Bharath
A M Bharath
Hello Lokesh,
Another question on the same lines:
– If there has to be another database column called “updated” [that represents the last “updated” time stamp – i.e., when an update query is executed in the DAO layer for an “edit employee information” functionality in the application], how would you achieve it?
Thanks,
A M Bharath
Lokesh Gupta
I will give preference to this solution:
https://stackoverflow.com/questions/221611/creation-timestamp-and-last-update-timestamp-with-hibernate-and-mysql
sats
Hello, Lokesh Gupta.
I’m doing everything written above step-by-step.
when trying to run the project I get:
log4j:WARN No appenders could be found for logger (org.springframework.web.context.ContextLoader).
log4j:WARN Please initialize the log4j system properly.
окт 17, 2013 2:04:09 AM org.apache.catalina.core.StandardContext startInternal
SEVERE: Error listenerStart
окт 17, 2013 2:04:09 AM org.apache.catalina.core.StandardContext startInternal
SEVERE: Context [] startup failed due to previous errors
[2013-10-17 02:04:09,503] Artifact Employee:war exploded: Error during artifact deployment. See server log for details.
What can I be doing wrong?
I’m using Intellij Idea 12, Tomcat 7
Lokesh Gupta
check server logs for deployment errors. Please provide logs.
sats
Here’s what I get:
–removed other logs
Caused by: java.lang.NoClassDefFoundError: Lorg/hibernate/cache/CacheProvider;
…
Lokesh Gupta
Which hibernate version? 3 or 4?
Verify if you are not making same mistakes.
https://stackoverflow.com/questions/7528862/exception-noclassdeffounderror-for-cacheprovider
https://stackoverflow.com/questions/11978094/java-lang-classnotfoundexception-org-hibernate-cache-cacheprovider-exception-wh
yogesh gandhi
after adding the aop jar (from spring 3.0.2 dependencies), i was getting a class not found error in tomcat logs.
To Fix that I had to change the BasicDataSource class, that is mentioned in employee-servlet.xml
Correct class w.r.t. tomcat = org.apache.tomcat.dbcp.dbcp.BasicDataSource
While earlier it was
Cannot find class [org.apache.commons.dbcp.BasicDataSource
Akansh Bhatnagar
Hi Lokesh, I am trying to run above code by I am getting below exception:
org.springframework.beans.factory.BeanDefinitionStoreException: Unexpected exception parsing XML document from ServletContext resource [/WEB-INF/employee-servlet.xml]; nested exception is java.lang.NoClassDefFoundError: org/aopalliance/intercept/MethodInterceptor
Please help in this.
Lokesh Gupta
Are you using example code or your own? Which spring version you have? Can you please check if this class is present in spring.jar? If you are using your own code then does it bundle ear file also?
yogesh gandhi
Dear Lokesh, I think you should add this solution to your post, as many people don’t read comments.
Add one troubleshooting section and this is majorly faced by all new commers
Lokesh Gupta
I will.
yogesh gandhi
please add com.springsource.org.aopalliance-1.0.0.jar to your classpath. This doesn’t comes directly with spring 3. This is a known problem with spring 3.0
See this link, it has given a clear cut solution…
http://javaprogrammingtips4u.blogspot.com/2010/04/resolve-javalangnoclassdeffounderror.html
wuchiwo
LazyInitializationException thrown since the session has been closed.
Kalyan
I cannot download the source code from the below link. Do you have any other link to download source code.
https://docs.google.com/file/d/0B7yo2HclmjI4clZVT0VxeGNERFk/edit?usp=sharing
Lokesh Gupta
What’s problem in this??? Go to file menu and click download.
John
Thanks Lokesh for the comments. I have resolved the above issue ..Currently facing another issue after resolving it. I am putting the stracktrace below. Can you pls tell me is it because of version mismatch of the jars. I am not sure about the error. Just a guess… Please find the stracktrace
Lokesh Gupta
java.lang.NoClassDefFoundError: org/hibernate/annotations/common/AssertionFailure
It says everything. Dependency missing. Make sure you hace correct pom.xml file.
Andrew
I tried to deploy the above application in Tomcat and getting the foloowing error. Please find the stracktrace below.. Any help will be appreciated..
Lokesh Gupta
Andrew, I tried many times but unable to replicate this issue. You see, for many others, it worked perfectly fine. So there must be something you are doing differently. Can you please list down the steps.
FYI, I did this:
1) Downloaded the project in eclipse workspace
2) Run prompt > mvn eclipse:clean eclipse:eclipse -Dwtpversion=2.0
3) Deploy the application on server
4) Access the URL: http://localhost:8080/Spring3HibernateIntegration/
Note: Make sure you have created the “employee” table in “test” DB
Nirmal
Hi
I have copied all the files along with the required jars. I am using spring STS and vmware Server for deployment.
Here I am connecting to DB using Oracle XE. But while launching the app, it’s throwing me http 404 error.
Is this right context root I am using? Need your help..
http://localhost:8081/Spring3HibernateIntegration/
Lokesh Gupta
Path is correct. Look for some error in server logs while deployment.
iswarya
could u plz explain me the same project using weblogic server
iswarya
thank you so much. and ur sample project helped me a lot.
thank u once again
Prashant
Great tutorial… It worked for me flawlessly….
Idree
I am getting null pointer exception
Lokesh Gupta
Please share the stack trace.
Idrees
Lokesh Gupta
Absolutely not helpful. I thought you was playing with my code sample, but it was something else. Better upload your code and share download link here.
Idrees
Hmm.. Ok this application is using Jersey spring and hibernate.. It is working using hibernate.cfg.xml using hibernateutils class, I want to convert that using session factory from application-context and inject that in DAOs.
and I am getting null pointer… I will see if I can put the code or provide download link.
Thanks for your replies!
Lokesh Gupta
I am already using autowiring, right? Read more about autowiring here: https://howtodoinjava.com/spring-core/spring-beans-autowiring-concepts/
Gowtham
Hi! I imported the entire project in eclipse. But in editEmployeeList.jsp the following ‘Can not find the tag library descriptor for “http://www.springframework.org/tags” ‘ for . Can you explain me how to resolve this……
Lokesh Gupta
Look at here: https://stackoverflow.com/questions/4219166/can-not-find-the-tag-library-descriptor-of-springframework
keda87
i’ve tried this tutorial with netbeans without maven and tomcat as server. and file structure it was same as on this tutorial. but i got an error like this :
SEVERE: Exception sending context destroyed event to listener instance of class org.springframework.web.context.ContextLoaderListener
java.lang.IllegalStateException: BeanFactory not initialized or already closed – call ‘refresh’ before accessing beans via the ApplicationContext
Anandan Rajendran
Hi,
I am using JBoss5.1. when i run the application i am getting the following error.
Lokesh Gupta
java.io.FileNotFoundException: class path resource [hibernate.cfg.xml] cannot be resolved to URL because it does not exist
Clearly file is not found where it is expected. Try to resolve this file path issue.
Also, verify the file in classes folder.
Lilliana
I had the same error, but it was beacause i put the hibernate.cfg.xml inside of this folders src/resources and the correct path was inside the source folder src/main/resources. Now the application is working correctly 😀 Thanks for this example and your help.
sudhindra
hi i am getting error like this:
type Exception report
message
descriptionThe server encountered an internal error () that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: javax.servlet.jsp.JspTagException: Neither BindingResult nor plain target object for bean name ’employee’ available as request attribute
root cause
javax.servlet.jsp.JspTagException: Neither BindingResult nor plain target object for bean name ’employee’ available as request attribute
note The full stack traces of the exception and its root causes are available in the GlassFish Server Open Source Edition 3.1.2.2 logs.
what to do..?
Lokesh Gupta
Make sure you have defined @ModelAttribute(value=”employee”) in controller. Please refer to code above. Its working and tested in tomcat.
Pradeep
I tried out this sample and it works great. However I have some doubts to solve my specific issue:
1. In the EmployeeDTO object has a object like Address which is say a different class, how do we create the
form since the form contains only one commandName.
2. Second, Can we make the controller class accept json request also. How?
Please let me know the solutions for the above two. Your help is greaty appriciated.
Regards,
Pradeep
Lokesh Gupta
1) You can pass HashMap to view. In this way, you can send multiple different objects (not associated together) within single command object.
Another way is to wrap all data in a class, let’s say, EmployeeAddressVO and set all data in this class and pass to view layer.
2) Absolutely. Use headers=”Accept=application/json;” is request mapping. A working example with XML: https://howtodoinjava.com/spring-rest/how-to-write-restful-webservices-using-spring-3-mvc/
Pradeep
I am planning to go with the first approach. Regarding your first reply: How can I populate the hashmap object and send it to the view? Also how to access the hashmap inside the jsp. Could you please eloborate?
Lokesh Gupta
Refer: https://stackoverflow.com/questions/736186/can-a-spring-form-command-be-a-map
sudhindra
run:
i am using netbeans ide….pls help..
Lokesh Gupta
I am sorry but I have no idea around netbeans IDE.
sudhindra
this is the code ,where i am getting error………
its a spring hibernate integration program
Lokesh Gupta
Sorry buddy, can’t help with only this much information. May be you can upload your project to google docs and provide a link here. Then only somebody can help you.
kehinde
Thanks. Though been new to the Spring world I think I have not gained my hands around some thing. Please can you prepare a war file of this so that I can just deploy it directly? Possibly it may the way I’m handling it that made me not get it. a war file for a beginner like me will be a very good start. Thanks.
deepak singh
hi Lokesh,
it worked after i added
on top of jsp page
thanks
Deepak singh
deepak singh
hi lokesh,
thanks a lot for the fantastic tutorial. good work.
I am facing a small issue.
${emp.firstname} and other data is not appearing on jsp.
though in the controller I could see the value of List..
do you have clue??
anmol
i am facing same the problem.
have you solved the problem?
please help me.
Alonso Isidoro Roman
thanks for sharing. I have learned that is possible to redirect to the same page using return “redirect:/”; but i have a question, if you are redirecting to / over any invocation controller methods, you are creating a new EmployeeEntity() and inserting over the map, even if it is not necessary, dont you think? Please share with us what you think.
otherwise, forgive my poor english, i am spaniard.
ken4ward
Thank you, Gupta. I have been on this for a while and it seems I am not yet getting somethings right because anytime I try to run the code, it generates this in the log file and it show 404 error, what should I do? Thanks.
Lokesh Gupta
Can you please list down the steps, you have done till now?
Have you downloaded the source code, or integrating of your own?
ken4ward
I downloaded the source code but implemented it on my own, not importing the code into Eclipse.
1. I downloaded the source code.
2. Created a web application project in Eclipse with the same name.
3. Created the application structure as it is indicated here.
4. Opened the pom.xml file and manually added the dependencies into the lib folder of the app.
5. Went to app Build path, go to the directory of the project and copied all the dependencies into the path as external jars.
6. Created files and just copy and pasted the codes from the forum here. Everything compiled fine, only the employee-servlet.xml flags a warning that javax.servlet is not found.
7. Deployed the application to Tomcat7.
Please I do not want to use Maven, it create a new learning curve for me, just want to try it out with webapps. The response is :”404 error”. Please help. Thanks.
Lokesh Gupta
I will suggest you to import first the downloaded sourcecode in some other application (with different name) and add all JAR dependencies you are using in existing project. Try to make it work first.
Once this application is successfully deployed and running, then you move code piece by piece into your new project.
ken4ward
Ok. Thanks. But what I’m trying to avoid is maven because I have tried with little success in configuring it. Please, if possible do you have a sample of this that is not implement Maven?
Lokesh Gupta
You can refer https://howtodoinjava.com/maven/ for maven installation and other simple tutorials. They are real easy.
Ajay
i am not able to download this project…Please can you mention the complete link..So in Just one shot i can download rar file..
Thanks,
Ajay
Lokesh Gupta
Use link in file menu : File >> Download
It will download the whole project
siddharth
where file? where download? i cant find these two… please explain from a-z how to download these application in a single shot ..
Thanks ,
Siddharth
Lokesh Gupta
Look at the bottom of post: “Download source code”. Its a link in bold. Click on that and proceed to download.
Siddharth
Yes i got it ….Thank you so much for explanation…
Ajay
Yes, i am able to do it…Thanks for nice explanation…
dharmendra
I reached this blog searching for annotation based Spring 3 and Hibernate 4 application in the hope that I will get rid of the xml configurations. But sadly this was not what I was looking for. Moreover, no where I found any tutorial for the same. Hence I wrote one. Putting a link here to benefit the users who might come here for what I was looking for.
To the admin: Please feel free to delete my comment and link if you think it to be offending.
Lokesh Gupta
Annotation based configuration is not the topic in this post, so it is not here naturally.
Brijesh
Thanks for sharing
Brijesh
Wonderful post. Thanks for your effort.
kaushal pandya
Yes , I am able to see the follwoing msg , but do;nt know why not working in CMD.
Browsing for this directory has been disabled.
View this directory’s contents on https://search.maven.org/ instead.
Lokesh Gupta
Your problem seems to be related to proxy which are normally configured in browsers, but not for CMD. Follow these instruction in given post to configure proxy settings for maven.
https://howtodoinjava.com/maven/maven-proxy-settings/
Kaushal Pandya
When i am running first command I am getting follwing issue, please suggest
Connection to http://repo.maven.apache.org refused
Lokesh Gupta
Are you able to access this URL from browser. Do you get any access denied error in browser?
Kaushal Pandya
Yes I am able to acces it .
JOO
i downloaded your source and imported it.
and i launched the application(http://localhost:8080/Spring3HibernateIntegration/) but it doesn’t work.
404 error message appeared
i am using tomcat
tell me anything how can i fix it T.T
Lokesh Gupta
Probably you have not setup the database. Check for tomcat console logs for deployment errors.
anil
sorry its a spelling mistake from my side…its working very fine..thanks for ur tutorial
Lokesh Gupta
Glad, you made it !!
anil
and 1 more thing i want to bring to ur notice is the records are not storing in db. when we restart the server the records which are inserted previously is not in db at all…. can u tell me whats the solution for it. as i need to write junit test cases the records has to be in db otherwise it will not pass.
Lokesh Gupta
Try settingupdate in
anil
ya its working fine now…i tried as u mentioned u above. prior to that i made an entry in employee-servlet.xml. as true even after autocommiting the records are not storing in db.. and at last i made a post to u.. thanks for ur advise
anil
tell me the url to launch the application
Lokesh Gupta
Its http://localhost:8080/Spring3HibernateIntegration/
Welcome file is configured as index.jsp in web.xml. So no need to type any relative URL.
anil
i did the same…i am using weblogic i typed http://localhost:9090/Spring3HibernateIntegration/ where i changed my port number to 9090
narendra
i am getting the below error while i run the application.
Lokesh Gupta
I does not look like programmatic error. Something is missing on runtime in DB.
Cyril
You have to create sequence for you table in the database.