Happenings

Data Mappers with Java

In the Java world, there have been many ways to persist and retrieve domain objects, and most involve some form of ORM mapping. Modern methods include Hibernate, iBatis, Spring JDBC Templates and other JPA providers; these are all fine methods and all should be used appropriately. Most of the time you should use one of the above approaches and not what I’m going to show you below.

One thing I’d like to say about persistence in Java is that you should almost never be using raw JDBC. There’s too much boiler-plate and repetition. You need to create a DataSource, and then get a Connection, then use that Connection to get a PreparedStatement. That can start to look pretty messy.

Worst of all is that you get a ResultSet back which, if used without any form of conversion or mapping to your own domain, exposes the rest of your application to the persistence layer. This is bad for several reasons, not least of all it makes your code more tightly coupled and brittle in the face of change. Let’s be clear here: passing around a ResultSet, CachedRowSet or any other variant is BAD.

It’s easy to avoid this problem by convert between a ResultSet row and a domain-specific object. Spring popularised an idea called the RowMapper (which I’ll outline below). The idea is that you have an interface that, once implemented, will convert between a resultSet and your domain object.

Why might you need this? If you’re dealing with legacy applications, it’s frequently too costly to go back and retrofit one of the more modern approaches to ORM; the database layer doesn’t fit well with Hibernate, or the rest of the codebase won’t sit nicely with JPA, or you can’t take an (additional) external library dependency for any number of reasons. Sometimes it’s easier to quickly roll your own. Here’s an example I’ll call a DataMapper (NOTE: I’ve omitted Exception handling for the sake of clarity, you will need to add this back in!):

public interface DataMapper<T> {

	public T mapRow(ResultSet resultSet);

}

That’s nice and simple. When you implement this interface, your implementation doesn’t bother with any sort of row iteration, all it does is take the current row of the resultSet, call the standard getString(...) etc methods and builds up a single one of your beans, here represented by the generic placeholder T. Elsewhere you have this partner method (I like to keep this as a statically imported utility):

public static <T> Collection<T> map(ResultSet resultSet, DataMapper<T> mapper) {
    Collection<T> mappedObjects = new LinkedList<T>();
    while(resultSet.next() {
        mappedObjects.add(mapper.mapRow(resultSet));
    }
    return mappedObjects;
}

This method takes care of the iteration. You pass it your resultSet, and a DataMapper implementation and it’ll give you back a collection of your domain objects. Still quite simple and neat.

How about an example? Let’s say you have a ResultSet that could be mapped to a simple Person bean:

public class Person {

    private String firstName;
    private String lastName;
    private int age;

    //getters and setters for the above fields are omitted
    //Imagine they were below. Go on, it'll make life easier.

}

To do this using the DataMapper code I’ve outlined above, you’d have something like this:

public class PersonMapper implements DataMapper<Person> {

    @Override
    public Person mapRow(ResultSet resultSet) {
        Person bean = new Person();
        bean.setFirstName(resultSet.getString("first_name"));
        bean.setLastName(resultSet.getString("last_name"));
        bean.setAge(resultSet.getInt("age"));
        return bean;
    }

}

Pass that to the map method along with a valid ResultSet and you’ll get out a Collection of Person beans to work with. We’ve gone from ResultSet to domain-specific in very little code.

Now these DataMappers don’t have to be simple. They could use the ResultSet and only the ResultSet, or they could use that as a basis to do more queries to build the object. They could lookup other services for information. They can do whatever you want for a relatively high power-to-lines of code ratio.

I’ve found myself using the DataMapper abstraction for the purposes of unit testing. You write a DataMapper that outright ignores the (perhaps empty) ResultSet you pass it, and it instead uses the some randomised test data you’ve got ready. You can now easily create test beans without relying on the DB layer.

It’s not perfect, and there are often better ways of doing persistence, but I’ve found this pattern has been very useful on a number of occasions.

Six Years of Solitude

So, as of the publishing date of this piece, Solitude will have been around and active for six years. It seems like a long time. Going back and looking over the first few entries is, as one might expect, cringe-inducing.

There’s the very first post (which promised the now long-defunct main VKPS site would be back soon – HA!) and first real update about Geolocation (which hasn’t really done much of any use, though we’ll see if Geode changes that), and the first film review (for The Tuxedo), and even the first first recipe (I remember how bad that omlette was, it was all shell).

Even though my post rate has dropped over the years, I hope that Solitude or a successor will still be here in another six years, to give me pleasant memories to wince over.

Neater Excel in Java

If you write applications or websites using Java, you’ve probably needed to export some data to Excel at some point or other. It’s pretty well accepted that the best library for this is the invaluable POI. It provides a neat wrapper over most Excel functionality. It lets you create or reference a spreadsheet (an HSSFWorkbook in POI terms), and then gives you object abstractations for just about any way you might want to manipulate that. Cell styles, formulas, drawing shapes… I won’t go into everything but the cook book is a pretty good starting point for any work you might be doing.

The one thing that’s always bothered me about POI is that it’s pretty low-level, you have to manage absolutely every aspect of what you’re doing. Now it’s great to be able to access that kind of power, but an abstraction over the top would be good.

That’s where jXLS comes in. It builds on top of POI to provide a templating approach to writing new Excel documents, a decent abstraction for most purposes.

Rather than managing everything from what can quickly become fairly complex Java code, you create a template excel file that contains placeholders for where your data should appear. It’s smart enough to be able to intelligently expand a collection of beans and create a new row for each one. That can reduce your boilerplate code significantly.

Downsides? The documentation isn’t the best, and the expression language for some of the more advanced uses is JEXL, which is pretty horrible. Those, however, aren’t major concerns. You’ll rarely need either in depth and, if in doubt, you can always drop down to the POI APIs anyway.

Now, it’s not to be used in all circumstances, there are still situations that are a little beyond it, but it’s an extremely good 80/20 API (you get 80% of the use cases made easy, and the other 20% are still possible). Definitely worth a look.

Film Fight 2009

After failing dismally in the early parts of last year, I’m going to be giving twittering Film Fight another chance (on my twitter feed). For anyone who didn’t see it last year, I’ll be writing film reviews before the later (and often delayed) monthly Film Fights with little snippets on twitter. Often this gives a slightly different perspective of the film, with less time for memory and external bias to change what I thought of the film.

I’m tempted to update twitter and not refer back to it for the film fight, so I can do a comparision of what I thought immediately and what I’m thinking now. We’ll see if that ever actually happens.

If you want to read the 2009 reviews but not the rest of my Twitter (which is occassionally more personal than Solitude), then use the Film Fight ’09 Twitter Search page.

Let’s hope I get a little further into this year than last.

Solitude Awards 2008

As has become tradition (see last year), it’s time for the best of 2008 awards here at sunny Solitude:

  • Best album of 2008 – I was struggling to come up with anything for this, mostly because I can’t really remember what I’ve gotten this year. Thankfully, my last.fm profile is handy for these things, once you mine past all the great older stuff I’ve been listening to. I think the best new album I got from this year is “West Texas” by Sleepercar. Formed as a side-project to Sparta, Jim Ward makes Alt. Rock and Country sit tidily, side by side. A pleasant listen.
  • Saddest band break-up of 2008 – It’s been a bad year for fans of modern rock, having lost the joint winners of this award. Reuben and Hell is for Heroes have both called it a day. Both bands were known for excellent live performances, solid albums and a great ethic. They’ll be sadly missed.
  • Most disappointing no-show album of 2008 – Overdue by quite some time, “Pandemonium Duke”, is the second album by Marmaduke Duke (made up of Biffy Clyro and Sucioperro members). We heard the first sampler well over 18 months ago and this record has been sitting on the shelves for quite some time. The plus side is that it now looks to be moving (first single is due out in February) and on a major label. Good times ahead for the Duke.
  • Best use of William Fichtner 2008 – While it would be easy to pick his ongoing role as Alex Mahone in Prison Break as his best use, I think we can do better. In the opening sequence for The Dark Knight, the joker and his goons rob a bank that is run by gangsters. The branch manager comes out wielding a shotgun and generally kicking ass. Who was it? Yeah, William Fichtner. Take that, Prison Break.
  • Best novel I read this year – I’m going to stretch this category a little (but only as far as others have before) and say the best novel I read this year was Watchmen. A densely plotted, well-imagined, gripping story covering so many themes and narratives that weave around each other so tightly that there’s no way to just mention a part. An incredible read.

And that’s it for 2008. Hope we have as much fun making up the 2009 awards, and you all have a good year. Keep your eyes peeled for Fichtner though, he’s hard to spot.