OracleSequence.

COMPONENT JAVA
Applying Design Patterns to JDBC: Building a Lightweight Object-Relational Mapping Framework
Frank Sauer
Listing 5. OracleSequence.


package com.trcinc.infrastructureservices.jdbc;
import java.sql.*;
import java.math.BigDecimal;

/**
 * Allows access to Oracle Sequences
 * @author  Frank Sauer
 * @version 1.0
 */
public class OracleSequence extends AbstractSqlOperation {

    private String next = null;
    private String curr = null;
    private boolean doNext = false;
    
    /** Creates new OracleSequence */
    public OracleSequence(String name) {
        next = "select "+name +".nextval from dual";
        curr = "select "+name +".currval from dual";
    }

    protected Object execute(Connection c) throws SQLException {
        ps = c.prepareStatement((doNext)?next:curr);
        ps.execute();
        ResultSet r = ps.getResultSet();
        if ((r != null) && (r.next())) return r.getBigDecimal(1);
        return null;
    }
    
    public BigDecimal getCurrentValue() {
        doNext = false;
        try {
            return (BigDecimal)execute();
        } catch (SQLException x) {
            return null;
        }
    }
    
    public BigDecimal getNextValue() {
        doNext = true;
        try {
            return (BigDecimal)execute();
        } catch (SQLException x) {
            return null;
        }
    }
  }