views:

1978

answers:

2

I'm using 2.5 and doing everything via annotations.

I have a simple form that allows the user to edit an object. The controller behind it creates the object and adds it to the model on GET, and processes the changes on POST (submit). It works fine, but I don't understand why. The object is never explicitly added to the session, and the object's "id" isn't passed to the submit method. How does the submit method of the controller know the object's "id" value?

The reason this question came up is that I have another form / controller that is nearly identical to the one above, but doesn't "work" unless I add the object to @SessionAttributes. The difference is that the object this particular controller works with has a reference to another object that is lazy loaded (I'm using Hibernate behind the scenes). When I submit the form without putting the parent object in SessionAttributes, I get a DataIntegrityViolationException because I'm never loading the referenced object.

When I add the parent object to @SessionAttributes the problem magically disappears. I say magically because even though I put the parent object into the session on GET, I still never explicitly loaded the referenced object, so it should be null (or an empty proxy or whatever happens).

What in the world is going on? I need some help!

+1  A: 

How does the submit method of the controller know the object's "id" value?

Controller doesn't know the "id". I think Spring creates new object using default constructor and populates form data into it. Hibernate must be think that this is a new object and stores it into database with a new id.

Aleksey Otrubennikov
+2  A: 

The object is most likely recreated during submit phase. The id might be "stored" in a hidden form field.

You should be careful with session attributes, I always try to avoid it unless I have a very good reason. In combination with Hibernate it can create all sorts of headache.

If you must, use a fully initialized copy.

henrik_lundgren