Monday, January 04, 2010

Hibernate3 Tip#5: Initializing Entity Objects

When you create entity classes, it is NOT a good idea to initialize entity references with defaults. Only initialize class attributes that are not references to other entities, and leave references NULLed, except the collections. A new identifier is assigned when a transient object is persisted, overriding whatever default you might have assigned. Having defaults may cause dirty checking to consider them changes that should be propagated to the database when merging or reattaching objects. For newly created objects, the dynamic update feature (if enabled) prevents sql statements that consist of null values (see this tip), and the database uses whatever the default is. (It is better for defaults to be defined in the @Column annotation).

When modifying objects, you only need change what needs to be changed, and if you have dirty checking enabled, only those changes will be propagated to the database. Also note that if you want to use a specific identifier for an object, you should call merge() to obtain a persistent version with that identifier almost immediately after initializing it. Otherwise you'll get a "detached object passed to persist ..." exception sometime when you attempt to commit the transaction. This is one pesky annoyance you discover only with experience.