After 8 months of development of a new project with extensive use of Hibernate I can now tell about my experiences with it. In general, Hibernate is a very useful tool. It saves a lot of time, because you don’t have to write SQL queries. If you make changes, you usually don’t have to rewrite queries, because there are only a few of them. The configuration using annotations is simple and powerful (and I personally prefer it to writing mappings in XML). Hibernate is able to generate database tables from mapped classes automatically and even update them as you add new fields to a class. Hibernate caching facilities are very useful. Finally, Hibernate allows to develop database vendor indepentent applications.
But there are few problems which I experienced:
- The most frustrating is in fact described in the Hibernate docs. An object returned by session.load() isn’t necessarily an object of the expected class:
Cat cat = (Cat) session.load(Cat.class, id); // instantiate a proxy (does not hit the db) if (cat.isDomesticCat()) { // hit the db to initialize the proxy DomesticCat dc = (DomesticCat) cat; // Error! .... }
- No inheritance mapping for value objects: here is the JIRA issue that never gets fixed, and a workaround.
- The strong suggestion in the Hibernate documentation to use a join table for every unidirectional one-to-many association (in the section 2.2.5.3.2.2. “Unidirectional”). Another suggestion is discussed here.
- 2nd level caching should be used with caution: after deleting an object the stale version can still stay in cache which can lead to an ObjectNotFoundException. I found no other solution except disabling the 2nd level cache for the class.