Tuesday, July 13, 2010

Spring 3: RESTful Web service Support... Take 2 with JPA and on Glassfish 3

In my original example. I just used a horrible static list in a controller as state for the CRUD methods. I couldn't leave it like that so I have now updated that version to use JPA to a MySQL DB.

This updated source code, config and POM files are available in SVN

I am not going to go through all the code like in my first example, but just go through a couple things I changed and new things picked up while making the change

1.
This thing, that actually cost me quite a bit of time...
The exception:
"A JDBC Driver or DataSource class name must be specified in the ConnectionDriverName property"

Which actually meant in my example
"I couldn't find your persistence.xml" imagine that... obviously very clear.

When you have a web application you can not just put your JPA persistence.xml in the META-INF folder like you would with a EJB application. Sad thing is I actually (after struggling for quite a while) remembered I had read this while studying for the SCBCD exam like 2 months ago. Doh!

So you need it in a META-INF in with your source, so you can either put in in a jar or if you lazy just have a META-INF in java/main/src.

2.
Trying to get Hibernate to run on Glassfish 3 was more effort that I thought it would be, and plain straight JPA was quick and simple.

3.
I used MySQL many years back, and it was alright. This latest version 5.2 Rocks... Seriously, go download the DB server, the divers and the Workbench.. The workbench is the winner... simple easy admin, almost instant EER / ERD diagrams, nice SQL query interface too, for my own home development I doubt I will look any further.

4.
For the last project I worked on we used Hibernate, and we used the generation tools to create our mappings and DAOs, which left us will a ton of Abstract and Implementation classes. I was never a fan of all those so went searching while doing this example and came across the Java Generic DAO implementation, which is very nice.

So you create a base DAO with the Key and Entity defined as generic parameters, just for ease of reading i went with "key" and "entity" instead of the usual K and E.


You then just have the following very small implementations just defining the actual Class type.


Very neat.

5.
In my original controller I had:
@RequestMapping(value="/users/", method=RequestMethod.POST) on each method.

Much nicer to have that on Controller level and just the following on the methods:
@RequestMapping(method=RequestMethod.POST)


6.
I mapped my dto purely through JPA annotations:

No comments:

Post a Comment

Popular Posts

Followers