March 28, 2008

An ORM-pattern merger

In today's post I will describe a pattern which I used in two projects so far and right now I don't really see a reason why I shouldn't use it again, I call it Generic EAO pattern. In fact, it's a merger of two patterns, namely the Generic DAO pattern which one of my former co-workers presented to me a couple of years ago and which he subsequently published on developerWorks. The other pattern is the Entity Access Object pattern presented in the book EJB 3 in Action.

I can quickly describe both patterns. The Generic DAO pattern uses Java Generics so you don't have to repeat the same CRUD-code over and over again to handle Entities. It's made for Hibernate but as you will see later, it works equally well in JPA.

The EAO pattern basically introduces an extra layer of abstraction. There are lots of discussions all over the internet whether the DAO (or in our case: EAO) pattern has died with the inception of EJB 3.0, where you can simply inject an EntityManager to your EJBs. Personally I have mixed feelings about it but I do accept the main argument given by the book, namely: What if you ever want to change persistence technology? You will probably end up rewriting all your EJBs.

However, the pattern as shown in the book left me wondering if I am not just writing lot's and lot's of code for nothing and thus the idea of merging two patterns was born.

So let's get started right away...

First of all, we need a generic interface for our EAO:

public interface BaseEAO<T, PK extends Serializable> {
void create(T t);

T read(PK pk);

T update(T t);

void delete(T t);

T refresh(T t);
}
Subsequently we build a generic EAO superclass:

public abstract class GenericEAO<T, PK extends Serializable> implements BaseEAO<T, PK> {
private static final String ENTITY_MANAGER_NAME = "java:comp/env/myPU";
private Class<T> type;
protected EntityManager em;

public GenericEAO(Class<T> type) {
this.type = type;
this.em = getEntityManager();
}

public void create(T t) {
em.persist(t);
}

public T read(PK pk) {
return em.find(type, pk);
}

public T update(T t) {
return em.merge(t);
}

public void delete(T t) {
em.remove(em.merge(t));
}

public T refresh(T t) {
if (!em.contains(t)) {
t = em.merge(t);
}
em.refresh(t);
return t;
}

protected EntityManager getEntityManager() {
try {
InitialContext ctx = new InitialContext();
return (EntityManager) ctx.lookup(ENTITY_MANAGER_NAME);
} catch (NamingException e) {
System.out.println("Unable to obtain EntityManager. This call will fail!");
return null;
}
}
}
In fact, if this class wouldn't be declared abstract, you'd be good to go already (provided the class using it has a type-level @PersistenceContext annotation, I'll explain this later, though...).

Create an interface for the EAO which we create in just a second:

public interface FieldEAO extends BaseEAO<Field, Integer> {
List<Field> findAllByType(String type);
}
And now let's implement an actual EAO which can be used in a Session Bean.:

public class FieldEAOImpl extends GenericEAO<Field, Integer> implements FieldEAO {
public FieldEAOImpl() {
super(Field.class);
}

public List<Field> findAllByType(String type) {
Query q = em.createQuery("select f from Field f where f.type = :type");
q.setParameter("type", type);
@SuppressWarnings("unchecked")
List<Field> list = q.getResultList();
return list;
}
}
As you can see, we didn't redo all the CRUD-operations, however, we did add a findAllByType-method which is specific to this Entity.

Now this is starting to look like something useful, however, we aren't quite there yet. Since all the classes so far are simple POJOs, the EntityManager-lookup in the InitialContext would fail. Why? Well, no persistence context has been created. We can do this by the previously mentoined type-level annotation. We localize this to a Stateless Session Bean which coincidentally also works as a factory, an EAO factory, to be specific:

@Stateless
@PersistenceContext(name = "myPU", unitName = "myPU")
public class EAOFactoryBean implements EAOFactory {
public FieldEAO getFieldEAO() {
return new FieldEAOImpl();
}
}
And naturally we need a local interface for this bean:

@Local
public interface EAOFactory {
FieldEAO getFieldEAO();
}
As you can see, the bean uses the @PersistenceContext annotation, which creates the persistence context for the EAO to use it.

Finally, some EJB might want to use it:

@Stateless
public class FieldFacadeBean implements FieldFacade {
@EJB
private EAOFactory eaoFactory;

public void createField(Field f) {
FieldEAO eao = eaoFactory.getFieldEAO();
eao.create(f);
}

public List<Field> findAllByType(String type) {
FieldEAO eao = eaoFactory.getFieldEAO();
return eao.findAllByType(type);
}
}
And it's local interface:

@Local
public interface FieldFacade {
public void createField(Field f);

public List<Field> findAllByType(String type);
}
Well, that's about it. Thanks to the excessive use of interfaces and the factory, you will easily be able to replace the JPA-specific implementation with any other data-access implementation

Note that you may want to expose the EntityManager's flush() method in the GenericEAO-class since there are cases where you may need it and there isn't any other way to get the EntityManager in the current design.

I definitely wouldn't consider it a best practice just yet and this pattern definitely has imperfections. If you have suggestions, questions or criticism, I'd love to know about it so leave a comment.

NOTE: Erik asked in a comment whether all entities will be detached. After getting a little uncertain if there is a previously undiscovered flaw in the pattern I set up a little test case and it does behave as expected. While the entities are in the scope of a transaction they will remain attached until the transaction commits (or aborts).

March 24, 2008

New toy, new joy

I must admit, for years I've had a love-hate relationship with IntelliJ IDEA and despite IDEA giving me plenty of headaches throughout the years I've always returned for it's (imho) superior code editor. Working as a consultant, though, you don't always have a choice and sometimes you are required to use Eclipse or (very rarely) Netbeans.

Looking at pre-6.0 versions of Netbeans, I've always felt that it was lagging behind in providing crucial features which the other two IDEs did have and thus I never really considered it to be my IDE of choice. Some months ago, though, I gave 6.0 a serious go and used it for one of my little home-brew projects and I was fascinated about how much features have been added, especially in the field of EJB 3.0-development.

While using it I discovered a number of extremely useful features such as integrated UML support, an enourmosly well-implemented Maven-plugin (Eclipse and IntelliJ-plugin writers, beware) and that it shared lot's of shortcuts with IDEA... oh joy! I also found a great feature which I find deserves more exposure: Design Pattern aids. You can actually apply a large number of GoF and J2EE Design Patterns to your existing code... I'm almost drooling just thinking about it and I rarely get excited that easily.

Naturally, I was excited when the first beta release of Netbeans 6.1 was announced about a couple of days ago and basically downloaded it right away and started experimenting with it the second I came home from work... well, truth be told, I already started using it at work. Thanks to using Maven as project descriptor it was easy to just open the same project in Netbeans without wasting a lot of time setting up the project in the new environment.

Anyway, let me share my first experiences with you...

At first glance not that much changed, except responsivness. Just as promised by the developers of Netbeans, the IDE actually does feel faster and not only in regards to startup-time but especially when doing code-completion actions which previously caused noticable lag in the IDE. This, of course, is my subjective opinion and I haven't performed any measurements. However, it's not about milliseconds with GUIs, it's about the performance as it is perceived by the user and in my case it's faster. One thing that did change is that Netbeans now shows memory usage by default, much like IntelliJ IDEA.

Besides that I found that editing of JavaScripts has become more "IDEA-like", it basically treats JavaScript just like any other code-file and thus you can things like code completion and most of the well-known refactorings.

I did notice a new feature called Shared Libraries which supposedly makes sharing projects with dependencies easier than before. I didn't give it a go myself, since I am normally using Maven, which handles dependencies differently anyway.

I find it also noteworthy that I discovered a number of new and updated plugins while surfing through the plugin repository. Amongst others I installed the new FindBugs plugin, neat! This is a nice and handy addition, at least for those checking the quality of their code with FindBugs (and you should... :D). Besides that I found that one plugin which I do use daily has been updated: The JBoss Application Server plugin. While I was unable to add JBoss 5.0 as an AppServer in Netbeans 6.0, it's now possible.

Ultimately, while scanning the beta for new features I found a number of other things, namely support for Sailfin (an extension to GlassFish which adds support for SIP) and JavaBeans (no, neither EJBs nor POJOs... actual JavaBean components).

However, where there is good there is almost always bad and this wouldn't be a very objective post if I didn't mentoin the bad things I discovered. One thing that I discovered is that the Create Facade for Entities-feature seems to be broken (at least in the build I am using). Bummer! Another thing is that I occasionally get a SAXException when going through the plugin repository and last but not least: sometimes dialogs don't refresh and the only way to fix it is to press Escape and reopen it. If you changed something that was worth keeping then you are in a bit of a pickle. I am trying to be forgiving about it, though... after all, it's still in beta!

March 16, 2008

Type conversion with JPA

If you've been in touch with JPA for a while you've probably encountered a number of limitations which may annoy you a little bit if you've used Hibernate before. One of those limitations is the lack of type conversion (something known as user-defined types in Hibernate) and I am trying to address it in this post.

The simplest example I can currently think of involves booleans and the lack of them in some databases like Oracle and MySQL (pre-5.0, that is). As it is right now, it's not uncommon to use a character-type column like Y/N or an integer-type column like 0/1 to mime a boolean in some databases.

As you may or may not know, in vanilla JPA you are unable to automatically convert this to a Boolean and thus you have some hideous Entity class like following:

@Entity
public class User {
  @Id
  private Integer id;

  @Basic
  private Character enabled;

  // ... getters/setters
}

Now this is just awful... You most definitely want to treat the property enabled as a Boolean in your code, but JPA just doesn't provide any feature to map the Integer automatically to a Boolean.

However, there are two easy ways to solve this! If you don't care much about portability of your application and run JBoss and/or know that you will always use Hibernate as your persistence provider you can actually use Hibernate-specific annotations to use features which are not normally provided by JPA. One of these features is to use user-defined (or Hibernate built-in) type converters.

Consider following Entity class:

@Entity
public class User {
  @Id
  private Integer id;

  @Basic
  @org.hibernate.annotation.Type(type=“yes_no”)
  private Boolean enabled;

  // ... getters/setters
}

You can see that I added a Hibernate annotation and in this case I use Hibernate's pre-defined yes_no type. This will automatically map the character to a boolean.

This works equally well with other types, however, as I said: This is not always portable to another AppServer and if you choose this approach, you should use the complete package name to the unportable annotations so it's clearly visible that something is a little odd :)

If you want your application to be fully portable without having to be concerned whether Hibernate is used as a persistence provider on another AppServer you may want to use the "manual mapping" approach (at least I call it manual mapping and you will shortly see why), so check this out:

@Entity
public class User {
  @Id
  private Integer id;

  @Basic
  private Character enabled;

  public Boolean getEnabled() {
    if (enabled == null) return null;
    return enabled == 'Y' ? Boolean.TRUE : Boolean.FALSE;
  }

  public void setEnabled(Boolean enabled) {
    if (enabled == null) {
      this.enabled = null;
    } else {
      this.enabled = enabled == true ? 'Y' : 'N';
    }
  }
}

This example is absolutely portable but you may end up clutter your entity classes with manual mappings in the getters and setters and before you realize you may want to use some sort of Utility class you might have duplicated a lot of code. Bummer!

As a final note I would just like to mentoin that the Hibernate annotation mentioned above is by far the only one you can use, you can check out the Hibernate Annotations API Javadoc to discover lot's of other features which make your JPA-experience more enjoyable and feature-rich.

March 2, 2008

Practical JAXB 2.0

Some days ago one of my former co-workers asked me about JAXB 2.0 as he remembered that I did some projects using JAXB while we were still at the same company. He is a real "do it yourself"-guy (at least that's my impression) and didn't put much trust in JAXB's Class Generator, XJC. He was concerned whether it really generates mappings which do exactly what he wants. And I understand why, XJC requires a well thought-through XML Schema file to work exactly the way you want it to and by exactly I mean: "somewhat close to what you want it to" :)

XJC, naturally, can't perform wonders and my impression is that many developers (in enough cases I can count myself to "those" developers) use following procedure to generate an XSD and ultimately the bindings:

1.) Create an XML-file.
2.) Use a tool of choice to generate an XSD.
3.) Run XJC

Naturally, the XML file is rarely a realistic representation of what you will get in the real world. You might just use one element by the name of product even though you may have an arbitrary number of products, you may have used used one string constant throughout your XML-file, and so on... Every XSD-generator works differently and some will use that one string as a constant, another one will say that there might just be exactly one of the previously mentoined elements, et cetara.

So, you have a sub-optimal XML, an even worse XSD and eventually run XJC. As I said, it can't perform wonders and thus you will suffer the consequences of not putting enough thought into describing your file.

In a perfect world you have a good XSD and XJC will do a very good job at generating your Java code, however, the code might still not be the way you want it to be. The two most common questions I've encountered (and which was also the case with my co-worker) are luckily quite simple to answer.

Firstly, how do I handle wrapper elements?

Say you have following XML:

<?xml version="1.0" encoding="UTF-8"?>
<catalog>
  <version>5</version>
  <name>IT Books</name>
  <products>
    <product>
      <name>Learning Java</name>
      <isbn>123-123456789</isbn>
    </product>
    <product>
      <name>Learning JAXB</name>
      <isbn>234-234567890</isbn>
    </product>
  </products>
</catalog>

In this case products is the wrapper for a number of product elements. Instead of mapping an own Products class you almost certainly want to have a List of Product classes.

To accomplish this just use the @XmlWrapperElement annotation in your Catalog class as such (it's a simplification so don't complain about the looks of the class):

class Catalog {
  @XmlElement(name = "version")
  int version;
  @XmlElement(name = "name")
  String name;
  @XmlWrapperElement(name = "products")
  List<Product> products;
}

Simple, isn't it?

Secondly, how do I map enumerations?

Suppose you have following XML:

<?xml version="1.0" encoding="UTF-8"?>
<cars>
  <car>
    <brand>Mercedes</brand>
    <price>50000</price>
  </car>
  <car>
    <brand>Audi</brand>
    <price>40000</price>
  </car>
  <car>
    <brand>Volvo</brand>
    <price>30000</price>
  </car>
  ...
</cars>


In this case we use brand as our enumeration, we just have three values which are used throughout the entire XML file, namely Mercedes, Volvo and Audi.

To accomplish this we do following (Cars class not included) files:

@XmlEnum(String.class)
enum Brand {
  @XmlEnumValue("Mercedes")
  MERCEDES,
  @XmlEnumValue("Audi")
  AUDI,
  @XmlEnumValue("Volvo")
  VOLVO
}

class Car {
  @XmlElement(name = "brand")
  Brand brand;
  @XmlElement(name = "price")
  int price;
}

Equally easy :)

In the end, I simply want to stress that a good XSD is the key to success whenever you do any kind of XML-processing (no matter if it's JAXB, JAXP or any other way) in your projects. It helps you make sure the XML is ok (you would be surprised how often customers send incorrectly formatted XML-files) and it defines a clear way for your parser (or code generator) on how to treat an XML-file.