Adam Bien's Weblog

Mapping JPA OptimisticLockException Into HTTP Status Code

A JAX-RS resource deployed as an EJB will wrap all exceptions into javax.ejb.EJBException:

public class ToDosResource {

An javax.ejb.EJBException can be easily transformed by an ExceptionMapper into a meaningful HTTP status code:

public class EJBExceptionMapper implements ExceptionMapper<EJBException> {

    public Response toResponse(EJBException ex) {
        Throwable cause = ex.getCause();
        if (cause instanceof OptimisticLockException) {
            OptimisticLockException actual = (OptimisticLockException) cause;
            return Response.status(Response.Status.CONFLICT).
                    header("cause", "conflict caused by entity: " + actual.getEntity()).
                    header("additional-info", actual.getMessage()).


        return Response.serverError().
                header("cause", ex.toString()).build();

The 409 status code

"...Conflicts are most likely to occur in response to a PUT request. For example, if versioning were being used and the entity being PUT included changes to a resource which conflict with those made by an earlier (third-party) request, the server might use the 409 response to indicate that it can't complete the request..."
is a natural HTTP representation of the OptimisticLockException.

The example above was taken from the DoIt sample application of the online course.

NEW workshop: HTML 5 and JavaScript Essentials, Three days in April 2017: from Java EE 7 Architectures over Microservices to Performance, Troubleshooting and Monitoring
On demand workshops: Java EE 7: Bootstrap, Effective, Testing and Microservices available for streaming.


A book about rethinking Java EE Patterns


This class represents a typical Java EE Anti-pattern. Some functionality is implemented somewhere, implements some interface, must be annotated with some annotation - but is completely detached from the context where it is used. The framework somehow does the magic, you "just" need to know the spell. In a nutshell one can see here the reason why Java EE has problems in terms of acceptance although being the most powerful and extensive platform available.

Posted by javaservant on October 09, 2015 at 06:55 PM CEST #

Hi JavaServant,

and the nice side of Java EE is: all the spells are clearly specified and do
not change a lot over the years. You only have to learn them once and then you will be able
to control a wealth of SPIs, providers and products.

Btw. I like the @Provider principle a lot -- it is a classic plugin pattern.

"(...)Java EE has problems in terms of acceptance (...)"? -> for me it looks more like explosion of Java EE projects. Whatever is Java EE related is more active / popular than ever...

So: learn once, apply anywhere :-)


Posted by on October 12, 2015 at 04:33 AM CEST #

Post a Comment:
  • HTML Syntax: NOT allowed
Online Workshops
...the last 150 posts
...the last 10 comments