christian wrote:
It's intrusive. A natural business key is not intrusive and the correct way to approach a custom identity routine. The business key might even include all scalar properties of a class. Or, in other words, the business key is what your application users would consider when "identifying an object". You should use this key to identify objects in the application logic.
OK, I'm a entirely new to Hibernate, but I'm trying to get as much of an understanding of the fundamental issues before diving in. It seems to me that identity is a pretty fundamental issue. As I understand it, the problem is:
1) The Hibernate ID (synthetic key) isn't assigned to a new object until it is saved. But, ...
2)Java collections require that an identity be static, or the collection may not function correctly. so....
3) the recommended approach is to define equals and hashCode in terms of something that is already defined. That is, a natural key. But, ...
4) the trouble is, a natural key is not always so easy to come by. In all the 9 pages of discussion on this, I don't recall an concrete example. So, let's look at the ones provided in the Hibernate 3.01 reference documentation: Work (section 23.2, Author/Work) lacks such a code (as title might easily be duplicated by different works. I assume that could be corrected with an ISBN number, but that assumes that you actually need and ISBN number for your entity. Adding one if it isn't required by the domain is as intrusive. On Person, "Jane Doe" might very well occur twice in a collection (Mother and Daugher authors). Or, more likely, business rules might require that it be possible to leave the name blank for some period of time.
5) One solution would be to alter the data model and create some sort of false candidate key(e.g. a UUID) assigned by the application. However, if the sole purpose of this is to avoid the problem for the short period of time that an object doesn't have a persistent object ID, then that seems intrusive, as well.
6) So a number of tricks have been proposed, each with their own shortcomings.
It seems to me that the basic problem is that the ID of an object should be assigned no later than the first time someone asks for it. That means that we use Hibernate's "assigned" ID generation facility. If I read correctly, it also means that we need to use an Interceptor, because otherwise Hibernate is forced to go to the database to determine if the object is transient and must be saved(reference doc, sec 5.1.4.
btw, the doc refers to Interceptor.isUnsaved, which apparently has been changed to isTransient, or something).
Is there some reason that
this approach will not work? The only downside I can think of is that you may end up burning a number of IDs in whatever mechanism that you use to generate them externally from hibernate, should you use the objects in question for something other than persistence.