When we choose an ID for our entities we have to decide between natural keys and surrogate keys. In case of surrogate keys we have to define the way this key is generated and the choices are quite a few. We can use a UUID, or a @GeneratedValue. The @GeneratedValue should define either a strategy (IDENTITY, SEQUENCE, TABLE) or a generator. A generator is a custom implementation that we create in our code and assign the ID to our entity before persisting in the database. The 3 strategies are not all supported by all RDBMSs. Also, they are not all as performant. The TABLE should be in general be avoided unless we want special portability features. IDENTITY should also be avoided because of the severe performance penalties but we use it if our database is not supporting it and the one that we favour is the SEQUENCE one. More details are given bellow:
IDENTITY - auto generation
Th ID is generated outside of the transaction, at database level. This means that in case of a rollback discards an already generated id leading to identity gaps. Another problem is the performance because we need a database hit in order to get the identity of the entity and use it in our code in case we need it. This restriction is interfering with the writhe-behind technique that Hibernate adopts. According to this technique, batch processing is utilised and no change is propagated to the database until a change is affecting the result of a query. When we need the ID to be generated, the batch processing is disabled by hibernate resulting in huge performance impact. Finally, we cannot use it with inheritance type Table-per-concrete-class. On the other hand, the generation of the id by the database is considerably more light weight than generating it on Java code.SEQUENCE
With this selection hibernate creates a sequence generator in the database and multiple tables and columns can use it. The advantage over IDENTITY is that it does not cause any issues with batch processing or inheritance. It can also preallocate values for improved performance.
Comments
Post a Comment