Hibernate and Composite keys
March 22nd, 2009
I like using surrogate keys for most of the database designs for the following reasons:
- Simplifies design and may improve efficiency
- Maintainability: Change to the meaning of the natural key could change the table structures when using natural keys
- Natural key values may be recycled
Having said that, we sometimes are forced to use natural/composite keys when stuck with a legacy database.
Here is a partial list of issues I have encountered when using Hibernate with composite keys on a legacy database:
- The documentation (or lack there-of) for Composite Keys usage poses big problems. But, the source code really helps .
- Inserts/Updates are slightly inefficient when compared to surrogate keys if there is no versioning strategy implemented.
- Cannot have relationships (with CRUD operations) mapped in hibernate for each of the keys in the composite primary key. A read-only collection mapping is possible by mapping the relationship with the same column (that is part of the Composite Key) and making insert=”false” and update=”false”.
- It is impossible to determine if the object to be saved is a new one or an existing one when using “assigned” composite keys. Since the keys are “assigned”, the primary key is not null and so it is hard to determine if this is a new object without making another call in a new transaction to the DB. This becomes very cumbersome.
- The Hibernate reference documentation uses various phrases like “discourage it for serious applications” for certain types of Composite-id mappings (embedded composite identifier). There are several issues with using key-many-to-one mapping in the Composite-id elements, etc.
- In older versions of Hibernate (before 3.3.x), you can’t use an IdentifierGenerator to generate composite keys. The suggested approach was to use UserType or CompsiteUserType. A lot of people choose to use “assigned” strategy to avoid the complications with custom types. I think this is resolved in the latest Hibernate version. Again, the documentation here is almost non-existent. In order to make this work in my code, I had debug through the Hibernate source code and also use the test case code attached in this Hibernate CR.
I am sure there are more, but I cannot remember them now. But, will blog as I remember them.
April 16th, 2009 at 2:12 pm
Хорошо пишете. Надеюсь, когда-нибудь увижу нечто подобное и на своем блоге…
September 3rd, 2009 at 9:06 pm
газ и уголь в России
Хорошо пишете. Надеюсь, когда-нибудь увижу вещь подобное и на своем блоге…