This forum is now a read-only archive. All commenting, posting, registration services have been turned off. Those needing community support and/or wanting to ask questions should refer to the Tag/Forum map, and to http://spring.io/questions for a curated list of stackoverflow tags that Pivotal engineers, and the community, monitor.

AnnouncementAnnouncement Module

Collapse

No announcement yet.

Best practice for posting entites via AJAX that have composite keysPage Title Module

Best practice for posting entites via AJAX that have composite keys

Sep 19th, 2011, 03:57 PM

So I understand that for entities that have composite keys, Roo creates an application conversion service for encoding/decoding a JSON string that represents the composite key using Base64 encoding. If I'm going to post an entity via an AJAX call, then I'll need to first get the encoded JSON string to submit that as the id field. So I'm wondering what the best practice might be. I'm thinking I can make one AJAX call, submitting the composite key fields as JSON and returning the encoded string. After that I can post the actual entity via a second AJAX call and use the encoded string as the id. I'm just wondering if there's a better way. Not sure if Dojo or some other JS library has a method for converting JSON to Base64 encoded strings so that it could be done in the browser and save a server request.

I would not recommend to create two separate calls just to post a single document to the controller. I would simply approach this by creating the converter you need for your use case by hand in the ApplicationConversionServiceFactoryBean so it can convert your document (whatever it looks like) in one go.

Comment

Hey Stefan, thanks for your response. What I was actually trying to accomplish is to use as much of what Roo generated. So posting my entity would use the POST request mapping generated by Roo in the controller's generated ITD. I managed to accomplish what I was looking for without making an extra AJAX request first for an encoded ID. I found some Dojo functions that allow me to encode in Base64. Here's the resulting JavaScript code.

So first I'm creating an id object and populating it. Then using a couple Dojo functions, I first convert the object to JSON, then encode it to Base64. Finally setting the value of a hidden input field who's id="id" to the resulting encoded string. Then when I perform my xhrPost to post the form, the id field contains the encoded composite key which gets converted back on the server. Resulting in a my record successfully being persisted.

One thing I might customize though is the POST request mapping. Since the Roo generated one actually returns a redirect to view the entity that was just persisted, I might create my own mapping which just returns a ResponseEntity with an HttpStatus of 201 CREATED and no body.