For those, who are not using maven for dependency management and are relying on downloaded jar files. I have created another project with all required jar files included in source code to download. Also, I have done integration using Spring 3.2.5 and hibernate 4. So if you fall into any of above two category, please read below linked post in case any problem.Spring 3.2.5.RELEASE and Hibernate 4 Integration Example Tutorial with All Jar files

To build this example project, I will guide you step by step. I this way we able to walk through some concepts also.

Step 2) Update pom.xml file to include spring 3 and hibernate dependencies. It will also include mysql driver added in project references. Now again execute command “mvn eclipse:eclipse -Dwtpversion=2.0” to reflect the dependencies in project.

As pom.xml file is too big so I am not writing it here in this post. If you want see the file, please download the project from download link and use it.

Step 3) Now lets decide out database table structure because it will be needed when we will write the entity classes in next step.

Step 4) Now its time to write EmployeeEntity.java. 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.

Step 5) 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.

Step 5) 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.

Step 8) 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.

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”

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?

fev 20, 2015 11:06:37 AM org.hibernate.event.def.AbstractFlushingEventListener performExecutions GRAVE: Could not synchronize database state with session org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:71) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43) at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:249) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:235) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:139) at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298) at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27) at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000) at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338) at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106) at org.springframework.orm.hibernate3.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:657)

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.

Getting below error. Please help!!! SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener java.lang.NoSuchMethodError: org.springframework.beans.factory.annotation.InjectionMetadata.(Ljava/lang/Class;)V at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findPersistenceMetadata(PersistenceAnnotationBeanPostProcessor.java:350) at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessMergedBeanDefinition(PersistenceAnnotationBeanPostProcessor.java:296) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyMergedBeanDefinitionPostProcessors(AbstractAutowireCapableBeanFactory.java:798) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:493) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) at org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:710) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:410) at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:276) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:197) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4797) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5291) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549) at java.util.concurrent.FutureTask.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source)

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.

SEVERE: Context initialization failed 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 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 java.lang.NoClassDefFoundError: ch/qos/logback/core/joran/spi/JoranException at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1146) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:296) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:293) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:628) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479) at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:389) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:294) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4701) at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5204) at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5199) at java.util.concurrent.FutureTask.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory com.howtodoinjava.dao.EmployeeDaoImpl.sessionFactory; nested exception is 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 java.lang.NoClassDefFoundError: ch/qos/logback/core/joran/spi/JoranException at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:517) at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:286) … 20 more Caused by: 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 java.lang.NoClassDefFoundError: ch/qos/logback/core/joran/spi/JoranException at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1512) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:521) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:296) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:293) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:912) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:855) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:770) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:489) … 22 more Caused by: java.lang.NoClassDefFoundError: ch/qos/logback/core/joran/spi/JoranException at org.slf4j.LoggerFactory.getSingleton(LoggerFactory.java:223) at org.slf4j.LoggerFactory.bind(LoggerFactory.java:120) at org.slf4j.LoggerFactory.performInitialization(LoggerFactory.java:111) at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:269) at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:242) at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:255) at org.hibernate.cfg.Configuration.(Configuration.java:151) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) at java.lang.reflect.Constructor.newInstance(Unknown Source) at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:148) at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:105) at org.springframework.orm.hibernate3.LocalSessionFactoryBean.newConfiguration(LocalSessionFactoryBean.java:821) at org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:552) at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.afterPropertiesSet(AbstractSessionFactoryBean.java:188) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1571) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1509) … 32 more Caused by: java.lang.ClassNotFoundException: ch.qos.logback.core.joran.spi.JoranException at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1676) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1521) … 50 more

Nov 15, 2014 10:37:11 PM org.apache.catalina.core.StandardContext listenerStart SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener 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 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 java.lang.NoClassDefFoundError: ch/qos/logback/core/joran/spi/JoranException at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1146) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:296) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:293) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:628) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479) at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:389) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:294) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4701) at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5204) at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5199) at java.util.concurrent.FutureTask.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory com.howtodoinjava.dao.EmployeeDaoImpl.sessionFactory; nested exception is 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 java.lang.NoClassDefFoundError: ch/qos/logback/core/joran/spi/JoranException at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:517) at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:286) … 20 more Caused by: 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 java.lang.NoClassDefFoundError: ch/qos/logback/core/joran/spi/JoranException at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1512) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:521) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:296) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:293) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:912) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:855) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:770) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:489) … 22 more Caused by: java.lang.NoClassDefFoundError: ch/qos/logback/core/joran/spi/JoranException at org.slf4j.LoggerFactory.getSingleton(LoggerFactory.java:223) at org.slf4j.LoggerFactory.bind(LoggerFactory.java:120) at org.slf4j.LoggerFactory.performInitialization(LoggerFactory.java:111) at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:269) at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:242) at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:255) at org.hibernate.cfg.Configuration.(Configuration.java:151) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) at java.lang.reflect.Constructor.newInstance(Unknown Source) at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:148) at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:105) at org.springframework.orm.hibernate3.LocalSessionFactoryBean.newConfiguration(LocalSessionFactoryBean.java:821) at org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:552) at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.afterPropertiesSet(AbstractSessionFactoryBean.java:188) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1571) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1509) … 32 more Caused by: java.lang.ClassNotFoundException: ch.qos.logback.core.joran.spi.JoranException at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1676) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1521) … 50 more

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 .

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.

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

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?

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

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.!!

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.

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”);

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

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)

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.

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 ..

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..???

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.

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?

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 Class ‘org.springframework.faces.webflow.SpringBeanWebFlowVariableResolver’ is missing a runtime dependency: java.lang.NoClassDefFoundError: org/springframework/web/jsf/SpringBeanVariableResolver It will be realy kind of you if u culd help me with this and explain the same thing with JSF. Thank you again

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.

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.

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.

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?

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 projectcd vollyballs

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.

Hello, can you help with this error? SEVERE: Error configuring application listener of class org.springframework.web.context.ContextLoaderListener java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1680) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1526) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4149) at org.apache.catalina.core.StandardContext.start(StandardContext.java:4705) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057) at org.apache.catalina.core.StandardHost.start(StandardHost.java:840) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057) at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:463) at org.apache.catalina.core.StandardService.start(StandardService.java:525) at org.apache.catalina.core.StandardServer.start(StandardServer.java:754) at org.apache.catalina.startup.Catalina.start(Catalina.java:595) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)

Could you please help me a problem. When i start Tomcat, occur an error. Although, I used the springweb jar in the library.

SEVERE: Error configuring application listener of class org.springframework.web.context.ContextLoaderListener java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1714) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559) at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:532) at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:514) at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:133) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4727) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5285) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)

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?

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.

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 ?

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.

How to solve this ? org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:659) org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:552) javax.servlet.http.HttpServlet.service(HttpServlet.java:617) javax.servlet.http.HttpServlet.service(HttpServlet.java:717)

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

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?

– 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 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

SEVERE: Context initialization failed 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 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 java.lang.NoClassDefFoundError: org/hibernate/annotations/common/AssertionFailure at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:609) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:469) at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:383) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:283) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:111) at org.a

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.

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.

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……

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 :D Thanks for this example and your help.

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.

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.

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?

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.

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??

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.

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.

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.

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.

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.

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

i am getting the below error while i run the application. SEVERE: Servlet.service() for servlet employee threw exception java.sql.SQLException: ORA-02289: sequence does not exist

at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112) at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:331) at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:288) at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:743) at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:213)