Archive for April, 2009

Hibernate and primary key unique constaint exception

Thursday, April 23rd, 2009

Its one of those things – you have the same problem every now and then, but not often enough to remember what the solution was.
I was implementing some hibernate code, but the tests for it failed due to primary key constraint exception (basically hibernate was trying to save already save object using same primary key). I can clearly remember that i have seen this exception before, but the cause and solution were lost somewhere between all those NonUniqueObjectExceptions and jsp exceptions that i had problems with few weeks ago :) .
So i had to dig into in once more, and promise to myself that i will blog it after i diagnose the problem, so i don’t forget about it ever again (and save someone else the trouble as well). So here it is:

The domain model and hibernate mapping were really basic – Descriptor object has reference to List of Note objects:


public class Descriptor{
    private Long id;
    private List<Note> notes = new ArrayList<Note>;

    public void addNote(Note note){
       note.setDescriptor(note);
       this.notes.add(note);
   }
   //getters and setters omitted for clarity
}
public class Note{
    private Long id;
    private String text;
    private Descriptor descriptor;
    //getters and setters omitted for clarity
}
<class name="Descriptor" table="t_descriptor">
        <id name="id" type="long" unsaved-value="null">
            <generator class="sequence">
                <param name="sequence">s_descriptor_id</param>
            </generator>
        </id>

        <list name="notes" cascade="all"
            <key column="descriptor"/>
            <index column="id"/>
            <one-to-many class="Note"/>
        </list>
</class>
<class name="Note" table="t_note">
        <id name="id" type="long" unsaved-value="null">
            <generator class="sequence">
                <param name="sequence">s_note</param>
            </generator>
        </id>
        <property name="text" column="text" not-null="true"/>
        <many-to-one name="descriptor" column="descriptor" not-null="true"
                     class="Descriptor"/>
    </class>

Looks simple, but when i run the test for the code above, i got dreaded primary key unique constraint exception.
After a bit of though, i was able to kick myself for not noticing the problem:
The notes property of Descriptor class is mapped with cascade=”all” meaning all save, updates, deletes with apply for the child objects as well. However, the inverse is set to false (inverse property is missing, defaults to inverse=”false”) – making both sides of the bi-directional relationship responsible of taking care of the relationship. SO Hibernate generates two insert statements, one because of cascade=”all”, and one as part of inverse=”false” rule.
The solutions is to set inverse=”true” on notes property mapping – this will make just one side of bi-directional relationship responsible for relationship, and the Hibernate will issue just one insert statement for the Note object.
Here is the correct piece of mapping:

        <list name="notes" cascade="all" inverse="true">
            <key column="descriptor"/>
            <index column="id"/>
            <one-to-many class="Note"/>
        </list>

Huh! Cascade and inverse properties when mapping collections in hibernate simplify the development, and improve performance if used correctly, but beware of the pitfalls of unsuspected exception.
To read more go to the Hibernate website or read this blog: http://www.codeweblog.com/hibernate-in-the-inverse-and-cascade/

The first Spring User Group in Manchester

Tuesday, April 21st, 2009

The first Spring User Group (SUG) event was held in Manchester on the 8th April at the Core Technology Centre in Manchester (a superb venue for anyone looking to hold an event in the North West). 46 people attended, which was fantastic for the first event and the feedback was all very positive. Attendees travelled from as far a field as Glasgow, Southport, the Midlands as well as Manchester and surrounding areas.

We were treated to practical demonstrations by Rob Harrop from Spring Source on Building REST applications with Spring Framework 3.0 and Jan Machacek from Cake Solutions on Building an application using the Spring Framework 3.0. The video of both talks can be seen at, http://vimeo.com/channels/opensourcecentral. The code for Rob’s talk can be found at http://github.com/robharrop/restlist/tree/master or for checkout users can simply do: git://github.com/robharrop/restlist.git. Jan’s code can be found at http://www.cakesolutions.net/teamblogs/2009/04/09/sug-source-code/.

The topics most requested for talks in future events were OSGI, Groovy and Spring security, we are actively arranging talks on these subjects. The consensus was that the SUG North West be run bi-monthly so the provisional date for the next meeting is the 3rd June 2009 at the same venue. If you want to be kept in the loop for future events or announcements please join the LinkedIn North West Spring User Group, e-mail me at guy@springusergroup.org.uk or visit the SUG website at http://www.springusergroup.org.uk/.

Building Spring 3 web applications

Thursday, April 16th, 2009

An update to the PDF is ready for download; I have included the cookbook service implementation and begun the discussion of the web application.

SUG source code

Thursday, April 9th, 2009

You can now download the source code for my talk here. You will need to modify the location of the HSQL data file. Currently, it is /Users/janm/Writing/s3wa/code/uk.org.springusergroup.s3wa.repository/src/test/db/t for the test database and /Users/janm/Writing/.../.../p for the “production” database. You will need to find the module-context-t.xml file in the repository and cookbook nodule and the module-context-p.xml in the repository module and modify the path to the database to suit your system.

Once you’ve done that, you can build the application. To do that, go to s3wa/trunk/build-s3wa and run ant test.

Once it says BUILD SUCCEEDED, you can open the project in IntelliJ IDEA or drop the war (in ../integration-repo/org.uk.springusergroup/org.uk...web/1.0.0/uk.org...web-1.0.0.war) into Tomcat.

Don’t forget to download the PDF chapter from the “Building Spring 3 web applications” post and keep an eye on that post for updates to the PDF.

The next Spring User Group

Thursday, April 9th, 2009

I have several ideas for the next SUG talk, I think they are all really exciting, but I will welcome your comments. The choices are:

  1. Securing Spring web and WS applications.
  2. Introduction to OSGi with Spring Dynamic Modules and dm Server
  3. Spring on the server side, Ruby on the client

Securing Spring web and WS applications

In this talk, we will take an existing, well-written Spring web application and crack it. We will use Mallory’s services and show script and XHTML injection, cookie stealing, the “other four” HTTP methods and — Mallory’s favourite — SQL injection.
Next, we will take another Eastern European, Eve, and we’ll show how we can snoop on WS messages, we will demonstrate how Mallory can modify the message. We will also show how we can cut Eve out and how we will detect that Mallory is making changes to our messages.
You’ll experience our Eastern European team at its dark, foreign and generally menacing best :)

OSGi, Spring DM and dm Server

We have done quite a bit of development using the dm Server and OSGi. We can show how to make most of OSGi in your new applications. We will show the usual tricks of updating dependencies at runtime, we will also show OSGi fragments and dynamically extensible web applications.
You will see web applications deploy and update in seconds!

Spring on the server side, Ruby on the client

This should please all of you out there who think that Java web applications with servlet, JSPs, taglibs, and all that are just too complicated for the task. In this talk, we’ll show how to have a complex (and easily load-balanced) services tier in Java and Spring and how to make the most of the agility of Ruby on the client. You’ll see loads of JSON and REST.
If time permits, we may sprinkle it with memcached magic dust.

Please comment

So, please help me decide which talk would go down the best. I look forward to your comments either in this blog or on my e-mail.

Building Spring 3 web applications

Friday, April 3rd, 2009

The saga continues; I have added a few more pages to the chapter, which is available to download here.
Keep an eye on this space, there will be much more to follow soon.

I am giving a talk at the Manchester Spring User Group on Wednesday; it will be a live demo. Yes, nail-biting, high-adrenaline demo. Well, for me at least. The attendees will be no doubt sitting comfortably, sipping tea and munching biscuits. As is British tradition.
You can download a “chapter” to read up or follow my talk.

UTF-8 encoding and Spring message sources

Thursday, April 2nd, 2009

I was working on a pretty much straight-forward web application. As usual, i used Spring’s org.springframework.context.MessageSourcesupport, to be more precise, i used standard implementation – ResourceBundleMessageSource. Simple configuration, as following:

<bean id="messageSource"
                 class="org.springframework.context.support.ResourceBundleMessageSource">
          <property name="basename" value="messages"/>
</bean>

My messages properties file was standard as well, country names, so i had something like this:

country.name.unitedkindom=UK
country.name.ireland=Ireland
country.name.belgium=België
country.name.iceland=Ísland
country.name.israel=Israel...

As you can guess, the problems developed with specific characters in country names(ë, Í…). When i run the application, i got ‘???’ characters instead of specific UTF-8 characters for countries (so ‘België’ become ‘Belgi???’).

After some research, and digging in Spring source code, i located the problem, and the solution!

The problem was that ResourceBundleMessageSource uses the standard java.util.ResourceBundle and
java.util.Properties, which only support ISO-8859-1 encoding – so no UTF-8 encoding, no support for any special French, Spanish or Asian characters.

The solutions is very simple, and it comes with Spring as well. Use ReloadableResourceBundleMessageSource instead! Here is the correct configuration:

<bean id="messageSource";
                     class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
         <property name="basename" value="classpath:messages"/>
         <property name="defaultEncoding" value="UTF-8"/>
</bean>

As you can see, we are now able ot set default encoding explicitelly, so the countries names in my example worked like charm. The only other change was that the basename is now specified as Resource, so i was able to use convenient classpath: identifier to specify my messages.properties wherever i need it in the source code