Thursday, 17 February 2011

Integrating Spring MVC and a "Real" Database

On the Spring MVC and WebFlow video training course, we build a system from scratch based around a book store. To keep things focussed on the web tier, we use a mock implementation of a service class.

Therefore, we can run the system up without worrying about setting up a database, getting the tables set up etc.

However, I've had a few requests from people who are stuck on "upgrading" their Spring MVC project that uses the Mock. They want to talk to a back end database but for some reason it isn't working.

The best way to work is to start from your Spring-MVC project, and make sure that is working. As on the course, you'll probably have a Dispatcher-servlet.xml file with the web-tier beans, and a separate application.xml containing the "middle-tier" beans.

Now write a production version of your service class, in the same style as on the fundamentals course (for example, service class calls a dao which uses a Spring template to read/write to the db).

As all of the above is covered in both courses, it's just a case of integrating your knowledge.

There are a couple of steps you might need to follow however:

1: Add in missing Jar files

Add in any JAR files that you need for your data access strategy. I used Hibernate 3 (the old XML mapping style, not annotations), and I added:

antlr-2.7.6.jar
dom4j-1.6.1.jar
hibernate3.jar
hsqldb.jar
javassist.jar
jta.jar

If you're using Hibernate with Annotations, or MyBatis or whatever, your dependencies will be different. I simply borrowed these JARs from the project I created on the Spring Fundamentals course.

Step 2: Ensure your mapping files are copied across (Hibernate XML only)

Now for an annoying complication: I'm using the old fashioned but still usable XML mapping approach to Hibernate. I have a file called Book.hbm.xml in my package "com.virtualpairprogrammers.domain".

However, this file is not being picked up by the build script we used on the Spring MVC course. When Eclipse compiles, it copies any non-Java files from the /src folder structure, across to the corresponding folder under /bin.

The ant compile task does NOT do this, however. So I need to manually add this step into my build.xml.

<!-- ensure hibernate XML files are also moved in the compilation -->
<copy todir="${bin}">
   <fileset dir="${src}">
      <include name="**/*.hbm.xml"/>
   </fileset>
</copy>
Note: this is added inside the compile target.

I've uploaded a full sample project to http://vpp-misc-files.s3.amazonaws.com/MVC%20Project.zip. These sample files will only be available for a short period, so grab them while you can.

1 comment:

  1. You are providing the "Integrating Spring MVC and a "Real" Database " Effective course..But I am beginner for this, Can i able to learn this "Spring MVC" with in 2 months?
    Cegonsoft

    ReplyDelete