Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
357 views
in Technique[技术] by (71.8m points)

java - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...