Manage a sequence database with Spring
Fabian Piau | Sunday September 22nd, 2013 - 07:36 PMIt 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.
You want to retrieve / increment the value of a database sequence and the Sequence Generator of Hibernate does not meet your needs (see the note).
Rather than go through a DAO with Hibernate code (or worse use JDBC), Spring can do it for you in 2 minutes…
- 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!
Recent Comments