Is there a way to dynamically choose a @GeneratedValue strategy using JPA annotations and Hibernate?
I am working on a product that will be supporting multiple database engines (Oracle, MSSQL, MySQL). For Oracle, I would prefer to use Sequences rather than a Sequence table to avoid potential concurrency and locking issues on a high-volume installation, but other database engines do not support sequences. Furthermore, I would prefer to use one sequence per table rather than a global sequence (such as hibernate_sequence), so @GeneratedValue(strategy = GenerationType.AUTO) won't work. Is there a way to dynamically choose the strategy at runtime?
Actually, Hibernate interprets both GenerationType.AUTO and GenerationType.SEQUENCE using its org.hibernate.id.enhanced.SequenceStyleGenerator. SequenceStyleGenerator is an id generation strategy that picks one of two strategies based on what the underlying database supports. If the database supports sequences, SequenceStyleGenerator uses sequences; if it does not, SequenceStyleGenerator falls back to using a "sequence table". This "mapping" of which generator to use is controlled by a setting: hibernate.id.new_generator_mappings. Setting that to true enables the behavior I just described above. Unfortunately, for backwards compatibility reasons, we had to default that to false. So to take advantage of that, you'll need to make sure that setting is set to true.
Further, you can configure SequenceStyleGenerator to prefer either a global sequence or sequence per entity if no name is given. This is controlled by a setting named prefer_sequence_per_entity
SequenceStyleGenerator is quite configurable in general. Have a look at its javadocs for more information: http://docs.jboss.org/hibernate/orm/4.1/javadocs/index.html?org/hibernate/id/enhanced/SequenceStyleGenerator.html