Manage a sequence database with SpringFabian Piau | Sunday September 22nd, 2013 - 08:36 PM
It is better to let Hibernate manage technical identifiers (primary keys). But, if you need to generate a business identifier, an Hibernate generator can be not enough. In my case, my business identifier was not generated all the time, I mean its value could also be set manually. Unfortunately, when the new element is inserted in database (unless I’m mistaken, but I did not find…), the generator always overwrites the value of my business identifier with a generated one.
A small and useful note (very technical) if you use Spring in your project.
- To do this, simply declare a new bean in the Spring configuration of your project:
<bean id='mySequenceIncrementer' class='org.springframework.jdbc.support.incrementer.H2SequenceMaxValueIncrementer'> <property name='dataSource' ref='<Name of your datasource>' /> <property name='incrementerName' value='<Name of your sequence>' /> </bean>
Note: there are several implementations of incrementer for different databases (I use H2DB but MySQL, PostgreSQL, Oracle, etc. are also available.)
- Inject this bean in the class of your choice.
- And now, you can do:
final Long newIdSequence = mySequenceIncrementer.nextLongValue();
Tested and approved!