I am a big fan of the Hibernate’s direct field access functionality. I am not sure why ”property” access is the default instead of “field”. Direct field access allows me to control the number of getters/setters that are actually needed from the DAO Client’s perspective.

I think using property access helps enforce better encapsulation of the data in the mapped/persistent classes. I have seen that most developers just use public getters and setters for all of the properties in the mapped class.

This creates problems for collections, especially. I seldom expose getters and setters for collections. I always use a combination of “addXXX(Obj)”, “removeXXX(Obj)” and “clearXXX()” (depending upon the need) instead of “get/setXXX”. This is for efficiency (as Hibernate uses a custom collection class) and better encapsulation.

The only situations where I do not use the direct field access are:

  • If the DB schema data type does not directly map to the mapped attribute in Java where a translation is required. This is mostly true for Legacy Database schemas and also where custom introducing custom SQL type mapping is not an option perhaps due to inconsistent use of the same data type in legacy applications.
  • If there are dependent (child) tables that have composite primary keys (which include the primary key of the parent table). In this case, for saving a new entity I would need to intercept the setter of the primary key of the parent table to set the appropriate fields in the child tables.
  • If I use lazy initialization, I would use property access for the primary key. This allows us to call persistentObj.getId() without completely initializing the proxy. This is applicable only for the “Id” field.
  • If there is any other need to intercept the getters/setters for whatever reasons (validation, logging, debugging, etc.). This is very unlikely.

Technorati Tags: , ,

One Response to “Hibernate direct field acess and encapsulation”

  1. Pharmacy Reviews Says:

    Written at the begining of the year yet still very relevant, you should add your twitter link, ill follow for sure :)

Leave a Reply

TOP