Extreme Java When vanilla Java is not enough

21Oct/090

Booleans in JPA (the portable way)

If you want to map a boolean value in JPA, you will have a headache if your RDBMS is Oracle. Since it does not support a boolean data type, you usually create a CHAR(1) 'Y'/'N' field and use a lot of bad words to describe the feeling you have when you find out that JPA does not support boolean-to-char convertion.

A nice and portable workaround is described here. The trick is to remember why getter/setter encapsulation is a good pratice - you can do a lot more than just plain old get/set:

private char enabled;
 
public boolean isEnabled() {
  return enabled == 'Y';
}
public void setEnabled(Boolean enabled) {
  this.enabled = (enabled ? 'Y' : 'N');
}