A while back, I blogged about how Hibernate named queries rock I found another reason why they rock today: it lets you hide what your persistent properties are called.
I had a problem in the system I’m working on where, for legacy purposes, we were using a single space character to represent a “no-value-entered” or null. A little odd, but that’s not what I’m writing about.
I thought that this was an ugly hack, and I didn’t want to have the Java code above that having to look for “is it a single space” instead of looking for an empty string. So to do that, I renamed the persistent property and made a new public property. Like this:
private String foo; public String getFoo() { return foo; } public void setFoo(String value) { assert value != null; foo = value; } /** @hibernate.property column="FOO" not-null="true" */ private String getFooPersistent() { return "".equals(foo) : " " ? foo; } private void setFooPersistent(String value) { foo = value.trim(); }
(You’ll notice that the persistent property is private; Hibernate doesn’t care what visibility you give your members, and using private members will help ensure that other code doesn’t use this persistence hack)
One side effect of this, however, is that Hibernate queries need to refer to the ‘fooPersistent’ property, not the ‘foo’ property. Annoying. However, if you use named queries everywhere, it’s easy to find the HSQL to change: you simply search the *.hbm.xml files!
Now all I need to do is get this system to use named queries consistently… 😉
A custom UserType would probably be a better solution for this. Then no need for “messy” code in your own domain objects.
Unfortunately, a user type (which would be better) isn’t an option yet; too many other complexities at the moment.