SpringMVC-Hibernate-Maven-Glassfish-Netbeans sample project

This post is a slightly modified version of http://viralpatel.net/blogs/2010/11/spring3-mvc-hibernate-maven-tutorial-eclipse-example.html

(For explanations, see the original blog) that uses the following tech stack:

Spring MVC (3.0.2.RELEASE), Hibernate (3.6.7.Final), JEE 6.0, JPA 2.0 (2.0-cr-1) and Spring (3.0.2.RELEASE).

Functionally both are same. This just works with the said tech stack as I have made the correct entries to work with Maven2.

The main modifications boiled down to the Project’s pom.xml and the fact that I had to add @Transactional to the service methods – otherwise I was getting runtime exception that said there was no active transaction.

Download the project and MySQL script files to get started. The application, once built (import to Netbeans and Build) – can be deployed to Glassfish.:

https://docs.google.com/open?id=0B6uhVH07AfMPZmZkYzA0MmItZjAzYS00MjliLTgxMzQtYmY3MTRiOGY1Njlh

MySQL script is here: https://docs.google.com/open?id=0B6uhVH07AfMPMGQ2MmQzYjYtOTMyNi00MmVjLWFkZDQtN2Q1MDdjNTJhMWFm

Advertisements

33 thoughts on “SpringMVC-Hibernate-Maven-Glassfish-Netbeans sample project

  1. Hello mate,

    I am deploying this project on Tomcat 7 which is running on a Linux Centos host.

    I have changed the project so whereever is references Contact it now references student. I can get the project to compile and unlike the original project the pom seems fine in terms of it’s dependencies.

    When I compile the app using Maven install through the SpringSource Eclipse, I get a war which I then deploy to Tomcat.

    The problem I then have is that Tomcat throws the following exception.

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘studentServiceImpl’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.gymsolutions.dao.StudentDAO com.gymsolutions.service.StudentServiceImpl.studentDAO; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘studentDAOImpl’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory com.gymsolutions.dao.StudentDAOImpl.sessionFactory; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘sessionFactory’ defined in ServletContext resource [/WEB-INF/spring-servlet.xml]: Invocation of init method failed; nested exception is java.io.FileNotFoundException: class path resource [hibernate.cfg.xml] cannot be resolved to URL because it does not exist
    org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:286

    I have not tried to simply deploy your app without any modification. Before I do so can you tell me if you have actually complled and deployed this an got it working 100%.

    Thanks for you work, I am new to Spring and just want to get a proof of concept running so I can run with it.

    • Hi Kris,

      It seems from the log that the container (Tomcat) in this case, is unable to find the hibernate.cfg.xml – “Invocation of init method failed; nested exception is java.io.FileNotFoundException: class path resource [hibernate.cfg.xml] cannot be resolved to URL because it does not exist”. Please ensure that the WAR that’s getting generated contains the said file in the classpath. i.e, inside WEB-INF\classes folder. Also, when referring to hibernate.cfg.xml in your Spring configuration, try appending the word “classpath” before your file name. Like so: “classpath:hibernate.cfg.xml.”

      Hope this helps.

      Regards,
      Trishul

  2. Thanks Trihul,

    That worked although Tomcat did not like classpath: so I just set it as ‘WEB-INF/hibernate…..’.

    Now I am in and although its not working perfectly I can see we are nearly there.

    Just one small thing for others using Maven embedded in SpringSource Eclipse, after maven install was run, the second time I tried it caused a random compile failure. In pom.xml

    org.apache.maven.plugins
    maven-war-plugin
    2.1.1

    false

    Basically I changed the version to 2.1.1 instead of the beta, this solved my problem. It’s a known problem…..but there you go with the joys of Maven.

    Once again thanks for you hard work. That said I am wondering apart from having Spring and Hibernate on my CV, are there not 100 other far more simple ways to access a db and insert some data. For example on my main project I use JDO, servlets and JSP and instead of 8 separate bits of code I have maximum 4. Why use Spring, just seems a sledge hammer to crack a nut.

    I am getting a few hibernate SQL issues (HQL) but I will sort it out. I will post if I need your help. Thanks for all your support.

    .

  3. INFO: Server startup in 7150 ms
    Mar 1, 2012 1:13:51 AM org.springframework.web.servlet.DispatcherServlet noHandlerFound
    WARNING: No mapping found for HTTP request with URI [/contactmgmt/] in DispatcherServlet with name ‘spring’
    Hibernate: select student0_.STUDENT_ID as STUDENT1_0_, student0_.ADDRESS_1 as ADDRESS2_0_, student0_.ADDRESS_2 as ADDRESS3_0_, student0_.ADDRESS_3 as ADDRESS4_0_, student0_.CITY as CITY0_, student0_.COUNTRY as COUNTRY0_, student0_.DATE_CREATED as DATE7_0_, student0_.DATE_MODIFIED as DATE8_0_, student0_.EMAIL as EMAIL0_, student0_.FAX as FAX0_, student0_.FIRSTNAME as FIRSTNAME0_, student0_.HOW_HEARD as HOW12_0_, student0_.MIDDLE_NAME as MIDDLE13_0_, student0_.MOBILE as MOBILE0_, student0_.NATIONALITY as NATIONA15_0_, student0_.NK_FIRST_NAME as NK16_0_, student0_.NK_SURNAME as NK17_0_, student0_.NK_TELEPHONE as NK18_0_, student0_.POST_CODE as POST19_0_, student0_.SALUTATION as SALUTATION0_, student0_.SURNAME as SURNAME0_, student0_.TELEPHONE as TELEPHONE0_ from STUDENT student0_

    Hmmm now I am getting this error which is clearly hibernate HQL related. Can’t work out what the issue is. I can connect remotely and internally to the DB over port 3306.

    Any ideas (once again thanks for your help)?

  4. Ok finally thank you Trishul, this is working.

    Awesome job!

    To others just here are a few stumbling jobs I found and how to overcome them.

    When using Tomcat (I am using Tomcat 7 on Linux JRE1.6 Centos 64bit)

    1. Make sure the hibernate.cfg.xml is in the classpath i.e. under WEB-INF, if you need to instead of using classpath: just put WEB-INF/hibernate.cfg.xml. This is configured in web.xml.

    2. I was using SpringSource as my IDE which is basically a rehashed Eclipse. Forget about trying to get all the .m2 maven respositary stuff working just use the repository stuff in Trishul’s pom.xml. m2 is a headache you don’t need at this stage. See above for my change to the compiler config.

    3. If you are going to change the table structure like I did, make sure you have your columns mapped correctly. I had convinced myself that I had a hibernate config issue and all that was wrong was my column names.

    4. If you are using Tomcat 7 and probably other versions of Tomcat as well. Remove the jsp config in web.xml which relates to the spring-form tags. You don’t need it and if you leave it in Tomcat will go looking for the tld in WEB-INF/
    rather than in the spring-mvc jar which is where it is. You will get an exception if you leave it in.

    I can categorically tell you this works 100% and Trishul has done an awesome job in making Viral Patel’s code work on a 2012 platform. Thanks go to Trisul and Viral Patel. We got there in the end.

    If you are having problems getting this working, stay with it. You can contact me at http://www.gpsoft.co.uk. Better still ask Trishul nicely.

    • Hi Kris,

      Thanks for making amendments that work for Tomcat. Good to know whenever stuff works 🙂 – and you also did a commendable job in finding out your issues and fixing them as well !! Ha ha ha…

      Cool. And thanks again for your comments. It makes my day !

      I also like the way you put it : “Why use Spring, just seems a sledge hammer to crack a nut.” You are absolutely correct. AFAIK, Spring actually stole the show when JEE standards like EJB 2.1 were becoming a royal PIA. However, with the upcoming JEE 6 standards and CDI, using Spring for new projects are again questionable. I believe every technology has its sunny days. Hopefully Spring will continue to innovate – leading to better and more maintainable products.

      Cheers !
      Trishul.

  5. The reason I am using Spring is a bit selfish, the size of the project does not warrant it. I will be honest I am using it to improve my CV. Next job is to get my head around Spring Security for login. Then I am going to need Spring SessionAttributes. May as well investigate license options for users at the same time. Apparently Spring can handle licensing too. Then I am going to integrate Jquery closely followed by Apache POI for generating Word documents. Wish me luck lol! Might even look at Google App Engine????? Cloud stuff scares me though, I like to know where my database is.

  6. Quick question say I want to add a new model and controller for something, lets say a quick form for users. So I would set up a POJO for the user table, a DAO access layer, a service and a controller, inside the controller I can specify different sub URL’s for editing, deleting etc.

    What I don’t get is how exactly you map the controller to the view. I would have a view being user.jsp. URL’s would be something like /user/delete /usr/add etc.

    In your example I don’t quite understand from the web.xml and spring-servlet configuration how the student.jsp view is initialised.

    • Hi Kris,

      Good luck with the numerous technologies you intend to put yourself through 🙂 To answer how Spring mysteriously finds the view, check the following section in the spring-servlet.xml:

      bean id = jspViewResolver (can't paste the code, the blog engine is wiping it off)

      What this basically does is that it tells the Spring container to resolve the “view” by finding out the corresponding JSP in the folder WEB-INF/jsp/. To find out more options of View Resolvers, read the following and all thy doubts shall be cleared 🙂 :
      http://static.springsource.org/spring/docs/2.5.x/reference/view.html

  7. Ok so in the current config I can change the name of the jsp file to anything I so desire. I changed it to bananas.jsp and compiled it no problem then tested it. I will continue testing and I will post my findings here.

  8. Ok so here is what I have found, thanks Trishul.

    So say you want to resolve a completely different view then you just add it to the return value in the controller class.

    In my example I changed the name of the view to bananas.jsp. The page still rendered correctly. I then added a new .jsp called bananas2.jsp. I recomplied and deployed with no errors. I then changed the return value from whatever it was to “bananas2.jsp”. Recompiled and deployed and I now get the contents of bananas2.jsp. I just added a paragraph to the html/jstl as a proof of concept.

    This will work with multiple controllers with no modification to the spring-servlet.xml configuration. Things only get more complex if you want to start messing around with other types of view JSF or velocity etc.

    Cheers Trishul you are like a modern day non-green Yoda.

  9. Now I have yet another idea for modifying this lot. Now clearly as an app a simple form is not going to cut the mustard. You need to make the whole thing XHTML transitional, add CSS, and various other HTML style gubbins (gubbins = old English phrase for random bits of stuff no one cares about but actually do something). You probably want to add a footer as well the header part probably includes a menu as well. Maybe you might split it up into META, header and footer. Basically you want to encapsulate your view and controller with nice html stuff. The question is, is there some flash spring way of doing this or is it just as simple as adding an include into your jsp pages. I do it with includes in other non-spring applications.

    I reckon that is the simplist and most elegant way of doing it, that said no doubt there is some mad 30 classes (teamed with a good 12 lines of xml ;o)) Spring way to do it which is considered best practice.

  10. Also what do you reckon in terms of Java Server Faces as a view technology vs plain old JSTL/Spring form tags/jQuery? I would say a standard stack gives you more control but JSF makes your life easier?

  11. Hello !
    I am trying to run the project using Tomcat 7 and I have the following problem :
    “ATTENTION: No mapping found for HTTP request with URI [/contactmgmt/] in DispatcherServlet with name ‘spring'”

    I have followed Kris’s advices :
    – I used WEB-INF/hibernate.cfg.xml instead of the classpath in spring-servlet.wxml
    – I didn’t change the table structure. I just run the sql script.
    – I removed the jsp config in web.xml

    Does someone have any idea what’s going wrong ?

    Thank you !

    Sebastian

  12. Hi Kris,

    Sorry for the late reply. I was travelling a bit 🙂
    I guess with most frameworks like JSF its ‘the stuff you get out of the box’ vs. ‘what aspects I want to stay in control of’. There’s no easy answer and there’s no one size fits all solution – and that’s why there are so many technologies and frameworks out there. If you want it on your CV, I guess JSF is a good one. But if you want fabulous looking webs – with decent maturity and in terms of industry acceptance – try Primefaces (http://primefaces.org/). I’ve used combination of JSP/JSTL/jQuery – but trust me – it gets quite messy with the jQuery/javascript stuff if you are not disciplined. That said, component oriented frameworks like JSF/Primefaces provide a much richer API and most of the times – they just work.

    So – here’s wishing you all the luck in choosing the one that fits you 🙂

    Thanks,
    Trishul.

  13. Thanks I will have a look at primefaces. I am pretty comfortable using JSF/XHTML/JSP/JSTL/Jquery in a mashup. I am a bit of a jquery tart. I think I could also go a step further and use a REST architecture and return data from the controller as JSON. I am going to look at this in the next couple of days. I set up a basic template using jsp:include which works and does the job for me, so I now have a menu and footer in place. A great example of KISS (keep it simple stupid ;o)) at work. That said if i can get JSF/primefaces to do the work for me, it would be stupid not to.

    I am also setting up a scope session so I can pass my currently selected object between controllers/services for the entirety of the session. I realised that @sessionAttribure does not quite do that as it is only viable within one handler, despite its deceptive name.

    Still not looked in depth at Spring Security, but I have a users table, class, DAO, Service, and Controller setup ready and working for when I do.

    Looked at Velocity, but don’t really see what you get is any better than JSTL/JSP. Also the docs/community seem to be a strange bunch.

    So much choice out there the best you can do is investigate and make an informed decision and then run with the stack. Enjoying myself very much indeed!

  14. Hi !
    I am trying to run the project but I have following errors. Could someone help me ?

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘contactController’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private net.sebpx.subgeste.service.ContactService net.sebpx.subgeste.controller.ContactController.contactService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [net.sebpx.subgeste.service.ContactService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

    Thanks !

    Tom

    • Hi Tom,

      Please check your full class name in the spring configuration file. It seems it just cant find the said class net.sebpx.subgeste.service.ContactService.
      Regards,
      Trishul

  15. Hi, I am new in spring MVC, I downloaded this project, when I tried to run it from Netbeans I got this page
    http://localhost:8084/contactmgmtWar/

    with error :

    HTTP Status 404 –

    type Status report

    message

    description The requested resource () is not available.

    Apache Tomcat/6.0.26

    Please your help is appreciated.
    thanks

    • Hi,

      Please check the following:

      a. have you renamed the war?
      b. is your tomcat running on 8084? it usually runs on port 80 or 8080.

      The 404 simply means that you are trying to access a resource that the web app server is unable to find. You just need to make sure that the URL mapping is correct. Try writing a simple JSP page and accessing it – and then maybe look at Spring configurations. There’s nothing better than the Spring documentations trust me 🙂

      Hope this helps and thanks for looking.

      Regards,
      Trishul

    • Thanks Karthik. If I understand your question correctly, the answer is that you I used Netbeans and in it, there is an option to add / edit project structure and mark the folder(s) that you want to treat as source folders. Hope this helps.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s