; last updated - 3 minutes read

Many best practices in the Java world involve mapping Java objects to other Java objects. More often than not, this is downright stupid. Both objects are more or less identical, but you have to write a lot of code to map object A to object B. Plus, you have to write the backward mapping, too. It goes without saying that this is a very error-prone task. Not to mention it's boring as hell, making the task even more error-prone.

This is why I start to roll my eyes every time someone asks me to map objects. Granted, the underlying design pattern has its virtues. Decoupling the front-end code from the back-end code gives you a lot of flexibility. But do you need this flexibility? Even if you do, is it worth the pain?

Mapping objects automatically

Nomin to the rescue. It's one of those little tools that come in handy. It allows you to write very compact Groovy scripts to map object. Even better, if the attribute names of the objects are identical, Nomin is able to figure out how to map the objects without you help. You don't have to write a script at all. All you have to do is to invoke Nomin and have it map the objects for you:

NominMapper nomin = new Nomin(); EntityA entityA = nomin.map(entityB, EntityA.class);

Advanced mappings

Nomin doesn't stop there. If the attribute names of the objects are different, you can write a Groovy script defining the mappings as a simple assignment. Consider this snippet I've taken from the Nomin documentation page:

mappingFor a: Person, b: Employee a.name = b.name a.lastName = b.last a.birthDate = b.details.birth // different object tree levels!

Note that these assigments aren't really assignments. Nomin uses a declarative approach. The line a.name = b.name defines both the forward and the backward mapping.

There are similar mappings for lists and collections. If you need even more flexibility, you can define the mapping of an attribute using a closure:

a.snn = b.employeeId convert to_a: { eId -> repositry.findByEmployeeId(eId) }, to_b: { snn -> repository.findBySnn(snn) }

But it's hosted on Sourceforge!

No, it's not. The project has moved to GitHub a couple of years ago. It's just that the new project site hasn't made it to the top of Google's index yet.

Download coordinates

The latest version of Nomin is available at Maven Central. If you're using Maven, add these lines to your pom.xml:

net.sf.nomin nomin 1.1.3

License

Nomin is available under an Apache V2 license, which should suit the needs of most teams.

Wrapping it up

In my eyes, Nomin is a game-changer. Previously I considered mapping a thing to avoid. I never understood the benefit of DTOs. I had a hard time mapping Hibernate Entities to JSF beans. I couldn't avoid it for technical reasons, but I didn't like that error-prone task that adds little value to you business. Nomin changes that. Now, mapping is a annoying nuisance, but nothing worse. Highly recommended!

Dig deeper

Nomin documentation


Comments