Skip to main content

How to get Next Value from a PostgreSQL Sequence in a Spring Bean?

In some cases you may need to get nextval of a sequence in your Spring bean, say for example you need to generate a CSV file with a unique id column.
 
In this tutorial, we are explaining how to create a sequence in PostgreSQL and how to get the next value from the sequence in a Spring bean.

Creating a sequence in PostgreSQL

First we will create a sequence named texient_uuid_seq in PostgreSQL. For this, execute the following command in the terminal:
-- Sequence: texient_uuid_seq

-- DROP SEQUENCE texient_uuid_seq;

CREATE SEQUENCE texient_uuid_seq
  INCREMENT 1
  MINVALUE 1
  MAXVALUE 9223372036854775807
  START 100000
  CACHE 1;
ALTER TABLE texient_uuid_seq
  OWNER TO postgres;
A sequence named texient_uuid_seq is created.

Defining the Beans

A straight forward approach would be to use plain sql as given below:
 
Query q = entityManager.createNativeQuery(
                "SELECT texient_uuid_seq.nextval from DUAL");
BigDecimal result = (BigDecimal)q.getSingleResult();   
return result.longValue();
Spring has some in-built classes to deal with sequences, those are:
  • DB2SequenceMaxValueIncrementer
  • OracleSequenceMaxValueIncrementer
  • PostgreSQLSequenceMaxValueIncrementer
All these classes implements DataFieldMaxValueIncrementer, so this can be used in your DAO classes without worrying about the implementation.
 
In this tutorial, we will use PostgreSQLSequenceMaxValueIncrementer to get the next value from the sequence texient_uuid_seq. Define the following beans in your application context:

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" 
  destroy-method="close">
 <property name="driverClassName" value="${texient.jdbc.driver}" />
 <property name="url" value="${texient.jdbc.url}" />
 <property name="username" value="${texient.jdbc.user}" />
 <property name="password" value="${texient.jdbc.password}" />
 <property name="maxActive" value="${texient.jdbc.pool.size}"/>
 <property name="validationQuery" value="${texient.jdbc.validationQuery}"/>
 <property name="testWhileIdle" value="${texient.jdbc.testWhileIdle}"/>
</bean>

<bean id="transactionManager" 
  class="org.springframework.jdbc.datasource.DataSourceTransactionManager" 
  lazy-init="true">
 <property name="dataSource" ref="dataSource" />
</bean>

<bean id="uidIncrementer" 
 class="org.springframework.jdbc.support.incrementer.PostgreSQLSequenceMaxValueIncrementer">
 <property name="dataSource" ref="dataSource" />
 <property name="incrementerName" value="texient_uuid_seq" />
</bean>

First, we defined a dataSource bean, then a transactionManager and finally a uidIncrementer bean. Let us concentrate on the uidIncrementer bean, there are two properties set, first the dataSource and the second, the incrementerName. incrementerName is nothing but the PostgreSQL sequence we created in the first step.

Getting the next value in a Spring Bean

Now let us write a utility bean named UidGenerator which returns the next value from the sequence.
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.jdbc.support.incrementer.
          PostgreSQLSequenceMaxValueIncrementer;
import org.springframework.stereotype.Component;

@Component
public class UidGenerator implements ApplicationContextAware {
 
 private static ApplicationContext context;

 public Long getUid() {
  PostgreSQLSequenceMaxValueIncrementer uidIncrementer = 
      (PostgreSQLSequenceMaxValueIncrementer)context.getBean("uidIncrementer");
  return uidIncrementer .nextLongValue();
 }

 public void setApplicationContext(ApplicationContext ac) {
  context = ac;
 }

}
Now you can inherit other classes from UidGenerator to get the next value from the sequence.

Conclusion

In this tutorial, we learnt how to get the next value of a sequence in a Spring bean. A detailed tutorial will be published soon on how to use a CSV file generator using Spring batch, stay tuned.

Comments

Popular posts from this blog

HDFC Bank introduces Missed Call Service to know Account Balance

Missed call is a powerful business tool in developing countries like India where customers give a miss call to specific phone numbers for getting account details, providing feedback, voting etc. On receiving a missed call from a registered phone number, the underlying app performs a phone number lookup and sends the data to the caller via text message(SMS) or records the call details for future processing.HDFC Bank recently introduced missed call service for its retail customers which allows to retrieve bank account details, mini statement etc. by simply giving a miss call to their toll free numbers.Following services are now available: 1800 270 3333 - Account Balance 1800 270 3355 - Mini Statement 1800 270 3366 - Request for new Cheque Book 1800 270 3377 - Request for Bank account statement Also you can download HDFC Mobile Banking Application by giving a missed call to : 1800 270 3344. Other banks providing missed call serviceAxis bank(known as Axis Dial) - 09225892258Bank of India…

Induction Cooker Showing an Error Code? Induction Cooker Error Codes Explained

Are you searching for Induction Cook-top error codes? Here you can find the error codes of all popular induction cooktops and how to troubleshoot it.

These are for your reference only, do not try to open your cooktop without proper safety measures, we advise you to call the service person if any servicing is needed.

If you want to know how Induction Cook-top works, read our previous article titled What is Induction Cooker? How Induction Cooker Works?.

Whirlpool Induction Cooker Error CodesError CodeErrorSolutionF0An internal error was detected.Disconnect power. Wait 5 seconds before reconnecting power. If the symbol appears again, call for service.F2The surface cooking area is too hot and has turned off.Remove the pans from the surface cooking area. "F2" will disappear when the surface cooking area has cooled. If you turn the surface cooking area back on and "F2" reappears, the cooktop is still too hot. Turn off the surface cooking area and allow it to cool.F4The po…

LICHFL - Generating Home Loan Statements Online

Generating an online statement from LIC Housing Finance Ltd is very easy, simply follow the below steps to create an online account with LICHFL and generate statements online! You may use the online generated statement as a proof for principal paid for a housing loan(under section 80C) and interest paid(under section 24) while filing income tax returns.Want to know how to save maximum income tax? Read our most read article how to save maximum income tax(opens in new tab).Before reading further, make sure you have the following information with you: Your Loan Account NumberSanctioned AmountStep 1 - Open LICHFL websiteVisit LICHFL website and click on the 'New Customers? Click Here' link(refer the below screenshot). Step 2 - Enter your loan account detailsFill in the following details: New Loan NumberSanctioned AmountDate of BirthSecurity Codeand click on the Submit button. Step 3 - Enter your personal detailsEnter your email address, a username and password and click on submi…