A key generator produces primary-key identifiers for persistent entities. Its configuration affects when an identifier becomes available, how inserts are executed, and how portable the mapping remains across database dialects. section 5.2.5 section 5.4
Choose a strategy by comparing identifier timing, database support, and operational behavior:
- Prefer pre-insert generation when application code needs the identifier before INSERT; a shared database sequence can provide it independently. section 5.2.5
- Treat auto-incremented columns, column defaults, and trigger-generated keys as post-insert strategies: the value is available only after the INSERT executes. section 5.2.5
- Use enhanced-sequence for portable behavior: it uses a native database sequence where supported and otherwise emulates one with a table containing a single column and row. section 5.2.5
- Treat GenerationType.AUTO as a dialect-dependent choice: Hibernate commonly resolves it to sequence or identity, which may not provide the desired efficiency or portability. section 5.2.5
Calling persist() generally queues an insertion rather than executing SQL immediately. Hibernate may assign an identifier at that point, but getId() can still return null when generation depends on the later INSERT; delayed execution also supports JDBC batching. section 5.2.5
Configure generators alongside entity mappings and primary-key choices. A sound generated key is non-null, unique, and immutable, while Java identity, object equality, and database identity remain distinct concerns. section 5.2 section 5.4
