Monday, January 28, 2013

JPA without Spring (or any DI framework)

JPA is the ORM defined by the Java Community Process, that is to say, it is a JSR (317). Previously to JPA, there were a couple of ORM occupying the scene, like Hibernate or iBatis. So the community realized Java needed it's own ORM.

As any other JSR, the specification is defined through some documents, some interfaces and abstract classes, a couple of tests, etc., and let the vendors to implements the details. There are three main JPA implementations: Hibernate, EclipseLink and OpenJPA

The idea, as always, is to program using the specification (classes,interfaces, annotations, etc) and make the implementation available in the classpath so the details are resolved at runtime. That gives you the freedom to choose the implementation that fits better for your project or to change it without touching your source code.

I've been working with JPA for a couple of years in different projects, and most of the time it's configured through a dependency injection (DI) framework like Spring, where the EntityManager is injected in some DAO class.

Although using a DI framework may be the most appropriate approach for plumbing JPA in an enterprise scenario, it is very interesting to dig a bit and see what happens in the underground. This helps a lot to understand what is part of the specification and what is part of the salad of framework you are using.


Friday, January 25, 2013

Annotation based validation with JSR 303 (Bean Validation)

Every time you work with objects, you might want to ensure their state (properties, also referred as collaborators) is valid. So when you build an object based on some given input, you must validate whether this input is appropriate.

JSR 303 (AKA Bean Validation) is an specification defined by the Java Community Process, with the purpose of having an standard mean for validating an object state. 
The idea behind this specification is to use annotations for declaring which restrictions or constraints are applied to an specific object property or even to the whole object. So instead of using some if(...) stuff, you use annotations in the object definition (the class).
As any specification, the community provides a high level design (some documents, interfaces, abstract classes, etc.) and let the vendors implement the details. In the case of JSR 303 there are two main implementations: Apache BVal and Hibernate Validator.

So let's take a peek:

public class Person {

         @NotNull
         private String name;

         ...
}