Wednesday, 12 June 2013

Second example: PathEntityMethodArgumentResolver

 Another thing we encounter regularly, is that we want to issue a POST request to a URL to execute an action on a domain object. As we prefer not to repeat the code to retrieve the domain object, we’ve created an annotation @PathEntity so we can do this:

Granted, we could also do this by overriding the Spring ConversionService, but as we’ll see in the next example this approach has it’s advantages. The code for the @PathEntity annotation and the PathEntityMethodArgumentResolver to handle it is this:

And this is the class to resolve parameters annotated with @PathEntity:

Registering this MethodHandlerArgumentResolver is as usual:

With these two classes in place, we can identify our domain objects with our REST resources (URL’s). When the controller method is invoked, we have an instance of the domain entity the URL represents. Note that outside a transaction, this entity is a detached entity (this is prescribed by the JPA specification). So we still need to call EntityManager.merge(Object) to persist any changes. 
Post a Comment