Integrating Hibernate with Spring 3 Web MVC

This tutorial on “Integrating Hibernate with Spring 3 Web MVC” incorporates:

  1. Hibernate Transaction Control
  2. @RequestMapping friendly URL’s. More on this specific Spring 3 Web MVC friendly URL topic here. (Alternative @RequestParam method here)
  3. A Generic DAO suitable for Hibernate operations with Spring 3 Web MVC. More here in this separate Generic DAO tutorial.
  4. Spring 3 Web MVC Dependency Injection (DI) and Inversion  of Control (IoC). More on DI and IoC here.
  5. Netbeans (7.1.1 used here but any version will do)

The complete Netbeans project is available for download here. The SQL for the project is included in the download in the WEB-INF folder.

Update: Jan 8, 2014

———–

The project originally available for download does not work with Netbeans 8 due to libraries that were in Netbeans 7.1.1 no longer available in Netbeans 8. Additionally, a comment below referencing Netbeans 7.0 .1 may suggest the same problem. This enforces the point that a dependency management utility is a much better means of building projects. To that end this project has been recreated using Maven. This ensures it will work irrespective of IDE version. In fact because it’s a maven project it’s not dependant on an IDE at all. It should work on any IDE that supports Maven. Netbeans of course, does support Maven. Here is the download link SpringHibernateCrudMvn for the Maven version of this application.

The POM is quite comprehensive in that it includes support for Spring, Spring-Security, Jackson, Hibernate, Hibernate-search and a bunch of other utilities. It can serve as a template to a certain extent.

—————————————————— (/End Update)


The Netbeans Spring 3 Web MVC with Hibernate Transaction control demo project uses a number of libraries shipped with Netbeans but it also requires two additional jar files.

  1. commons-beansutils-1.8.3.jar
  2. aopalliance-1.0.jar

The libraries shipped with Netbeans  that are used in this project are:

  1. Hibernate
  2. Hibernate JPA
  3. JSTL 1.1
  4. MySQL JDBC Driver
  5. Spring Framework 3.0.6 RELEASE
  6. Spring Web MVC 3.0.6 RELEASE

Most of these libraries have newer versions (at time of writing so in fact it is best not to use  the libraries shipped with Netbeans 7.1.1 but rather download and use the latest version of each library)

The Project

This project performs CRUD (Create Retrieve Update and Delete) operations on Blog objects which have child Comment objects.

I.e. One Blog can have many Comments.

There is no Validation and no Authorization.

Setup

The database used is a MySQL DB with name ‘test’

 

Configuration

The project looks like this:

Spring 3 Web MVC Hibernate Transaction Control in Netbeans project setup image

The project is available for download here

Points to note in web.xml

The welcome file maps to this NavigationController method

This differs from the way in which a spring project is configured with the Netbeans Spring plugin. For more on how to setup a Spring 3 Web MVC project using Netbeans correctly, see this tutorial. For more specifics on the welcome page see this tutorial.

The <context-param> <param-value> points to the application context configuration file.

 

Points to note in dispatcher-servlet.xml

Telling spring to look in the classpath for a file called jdbc.properties which it will use to populate variables in this XML file.

 

Telling Spring to scan from top level package com.outbottle and expect annotations on various classes there.

 

Because, each URL request goes through the Spring dispatcher servlet, and subsequently directed to a controller method, it’s necessary to make provisions for exceptional URL’s such as css files (or images). Adding this tells spring to look in /WEB-INF/css for CSS files whenever css is specified in the URL. CSS files are now imported into the jsp fiels as so:

 

All this is somewhat self explanatory by examination.

Transaction control is deligated to the “hibernateTransactionManager” which is defined as
“org.springframework.orm.hibernate3.HibernateTransactionManager”

the <property-name = sessionFactory part means that anywhere a member variable called “sessionFactory” is found in code, it will be instantiated via this configuration.

The “sessionFactory” is configured with several of many possible Hibernate Configuration properties.

 

Points to note in the rest of the code

Each service class implements an interface in order to truly avail of DI and IoC. Althoughh not demonstrated here, the use of interfaces will make unit testing much easier. Chan ge is also facilitated easier.

The DAO (Data Access Objects) classes extend an abstract class thus facilitating the same. Note that Dao.java is a generic DAO which facilitates ease of pagination and querying etc which you may find to be os use. More on this specifically, here.

Each DAO class extends the Generic Dao class which facilitates specific querying. This is demonstrated well in the code.

Each Service concrete class has the @Service annotation. The value in the annotation, matches the member variable name in the controller class.

E.g.

@Service(“blogService”)

in BlogService.java

matches

@Autowired
private BlogService blogService;

in BlogController.java

Similarly with the @Repository annotations in the Dao classes matching the @Autowired members in the service classes.

Transaction Control is by default set to “read-only” on each service method by declaring the whole class

@Transactional(propagation = Propagation.SUPPORTS, readOnly = true) but the

but the readOnly attribute changes to “false” on any method where data is updated in the DB.

Propagation.REQUIRED means

“Support a current transaction, create a new one if none exists”

The different options for this are here in the Java Docs

Propogation.REQUIRED obviously suits in this example as each service method is designed to be an atomic transaction. Other options may be useful when more than one service method is to be used in an atomic transaction.

I.e. Annotating a service method as so means that a transaction is begun at the start of the method, closed and committed (where applicable) at the end of the method.

The commandName=”” in the jsp forms matches the name in @ModelAttribute(“”) in the controllers.

E.g.

BlogController.java

@ModelAttribute(“TBlog) ==>> commandName=”TBlog”

blog/delete.jsp

<form:form action=”{cp}/blog/delete” method=”POST” commandName=”TBlog”> …. </form:form>

In fact, this example project will still work without this match but, other issue may arrise upon expansion of this project if this matching is not correct

 

Project Download

SpringHibernateCrudMvn (Maven version. RECOMMENDED download)

 

All Comments welcome as always….

Hope this was helpful.

 

13 Comments

  • Excellent example ; I have used it for a Spring intro class at a community college (gave you credit of course). Thanks very much for posting it ; it’s clear, elegant, and it works !

  • I noticed that the entities were generated by Hibernate Tools 3.2.1.GA. I looked around and couldn’t find this as being an option for NetBeans; it was only good for Eclipse. Would you please comment on the best way of getting the class easily generated like Hibernate Tools? Thanks!

  • i got this error when i run in netbeans 7.0.1
    But i have this file (build-impl.xm) in correct path…

    FAIL – Deployed application at context path /SpringHibernateCrud but context failed to start
    D:SpringHibernateCrudnbprojectbuild-impl.xml:742:
    The module has not been deployed.
    at org.netbeans.modules.j2ee.deployment.devmodules.api.Deployment.deploy(Deployment.java:210)
    at org.netbeans.modules.j2ee.ant.Deploy.execute(Deploy.java:106)
    at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:291)
    at sun.reflect.GeneratedMethodAccessor47.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
    at org.apache.tools.ant.Task.perform(Task.java:348)
    at org.apache.tools.ant.Target.execute(Target.java:390)
    at org.apache.tools.ant.Target.performTasks(Target.java:411)
    at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1399)
    at org.apache.tools.ant.Project.executeTarget(Project.java:1368)
    at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:41)
    at org.apache.tools.ant.Project.executeTargets(Project.java:1251)
    at org.apache.tools.ant.module.bridge.impl.BridgeImpl.run(BridgeImpl.java:284)
    at org.apache.tools.ant.module.run.TargetExecutor.run(TargetExecutor.java:539)
    at org.netbeans.core.execution.RunClassThread.run(RunClassThread.java:153)
    BUILD FAILED (total time: 17 seconds)

    • Hi Udhay

      It may be that the libraries between netbeans versions 7.0.1 and 7.1.1 are different. This may be causing the problem. I’ve recreated the project using Maven. The blog has been updated to mention this. A download link to the Maven project in included. ( http://outbottle.com/wp-content/uploads/2012/05/SpringHibernateCrudMvn.zip ). You should try use instead of the original project.

      One thing to note though (and i may be wrong), when running a Maven project in Netbeans, Netbeans will ask about which application server to use, it will give you ‘just-once’ option and a ‘remember this’ option. On Netbeans 7.x if you choose the ‘remember this’ option, I think the POM is updated which can in fact cause problems. Netbeans 8 does not update the POM. Your best bet is to choose the ‘just this time’ (or whatever it is) option initially to run the project. If you’re feeling brave choose the ‘remember’ option but if it won’t run, just revert the POM file and run again.

      Let me know if that solves your problem.

      This should be a lesson to all reading this (myself included) that a dependency management system such as Maven or Gradle should be considered essential for all but trivial prototype projects.

      John

  • i am getting this error pls help me…
    init:
    deps-module-jar:
    deps-ear-jar:
    deps-jar:
    library-inclusion-in-archive:
    library-inclusion-in-manifest:
    compile:
    compile-jsps:
    In-place deployment at C:UsersMANIDocumentsNetBeansProjectsAddNamebuildweb
    Initializing…
    deploy?DEFAULT=C:UsersMANIDocumentsNetBeansProjectsAddNamebuildweb&name=AddName&force=true failed on GlassFish Server 3.1
    Error occurred during deployment: Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 17 in XML document from ServletContext resource [/WEB-INF/applicationContext.xml] is invalid; nested exception is org.xml.sax.SAXParseException: cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element ‘context:annotation-config’.. Please see server.log for more details.
    C:UsersMANIDocumentsNetBeansProjectsAddNamenbprojectbuild-impl.xml:734:
    The module has not been deployed.
    at org.netbeans.modules.j2ee.deployment.devmodules.api.Deployment.deploy(Deployment.java:210)
    at org.netbeans.modules.j2ee.ant.Deploy.execute(Deploy.java:106)
    at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:291)
    at sun.reflect.GeneratedMethodAccessor398.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
    at org.apache.tools.ant.Task.perform(Task.java:348)
    at org.apache.tools.ant.Target.execute(Target.java:390)
    at org.apache.tools.ant.Target.performTasks(Target.java:411)
    at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1399)
    at org.apache.tools.ant.Project.executeTarget(Project.java:1368)
    at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:41)
    at org.apache.tools.ant.Project.executeTargets(Project.java:1251)
    at org.apache.tools.ant.module.bridge.impl.BridgeImpl.run(BridgeImpl.java:284)
    at org.apache.tools.ant.module.run.TargetExecutor.run(TargetExecutor.java:539)
    at org.netbeans.core.execution.RunClassThread.run(RunClassThread.java:153)
    BUILD FAILED (total time: 17 seconds)

  • I don’t have any error in this program…
    But when i run i get this error…

    Initializing…
    deploy?DEFAULT=C:UsersAdministrator.MANI-PC.001DocumentsNetBeansProjectsSpringHibernateCrud1buildweb&name=SpringHibernateCrud1&force=true failed on GlassFish Server 3.1
    Error occurred during deployment: Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 21 in XML document from ServletContext resource [/WEB-INF/dispatcher-servlet.xml] is invalid; nested exception is org.xml.sax.SAXParseException: cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element ‘mvc:resources’.. Please see server.log for more details.
    C:UsersAdministrator.MANI-PC.001DocumentsNetBeansProjectsSpringHibernateCrud1nbprojectbuild-impl.xml:732:
    The module has not been deployed.
    at org.netbeans.modules.j2ee.deployment.devmodules.api.Deployment.deploy(Deployment.java:210)
    at org.netbeans.modules.j2ee.ant.Deploy.execute(Deploy.java:106)
    at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:291)
    at sun.reflect.GeneratedMethodAccessor168.invoke(Unknown Source)
    etc…
    BUILD FAILED (total time: 36 seconds)

    In server log:

    SEVERE: Exception while loading the app
    SEVERE: Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 21 in XML document from ServletContext resource [/WEB-INF/dispatcher-servlet.xml] is invalid; nested exception is org.xml.sax.SAXParseException: cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element ‘mvc:resources’.

    Is this software configuration error or any other issue?

    Reply pls ASAP…

    • Hi Udhay

      It looks like you’ve added a mvc:resources element to dispatcher-servlet.xml

      You therefore need to add the corresponding namespacing to the XML.

      I.e. Copy all the attributes from the beans tag in spring-servlet.xml and add them to dispatcher-servlet.xml

      xmlns:mvc=”http://www.springframework.org/schema/mvc” etc.

      That should do it.
      I’m not sure why you would need to do that though as spring-servlet.xml has mvc:resources already.

      Side note: As you’re using glassfish. Put a “/” on the end of the URL when the index page loads initially. This will make relative links relative to the context path and not the domain. I’ll update the maven download with this fix later.

      Please let me know if this works. I’m happy to help.

      John