Tuesday, July 5, 2011

Requirements for object to become Hibernate Object

A Hibernate object, suitable for mapping into a database, is a normal java bean with a number of extra requirements.
  • There must be a default constructor for the class.
  • There must be accessors and mutators for all the instance variables of the class. Actually this is overstating the requirement but is a good base rule: read the Hibernate documentation for the full details.
  • The class should implement Serializable. Strictly speaking, this is not a requirement. However, in practice you will normally want your Hibernate objects to be serializable so that they can be (potentially) migrated around a multiprocessor cluster or saved and restored across a web server reboot etc.
  • The class should have an id instance variable, usually of type Long. Again this is not a true requirement but it is recommended to use automatically generated surrogate keys and, if so, to use an instance variable called id to hold it. Certainly, alternatives are possible.
  • The mutator for the id property should be private, not public. Again not a requirement but good practice. You should never update the id property directly but rather rely on Hibernate updating it for you. In practice, it is the value of this field that Hibernate uses to decide if an object has been mapped to a database record or not. Change the property yourself and you could seriously confuse Hibernate.
  • You should decide on a business key for the object and implement the equals and hashCode methods for it.
  • You should add any extra type specific constructors (which should leave the id field null) and business rule methods you like.
  • You should not make the class final if you want to be able to use lazy loading for objects of the class.

No comments:

Post a Comment

Chitika