andcsie
andcsie

Reputation: 398

Oracle sequence does not increment from Java/Hibernate

I have the following function which calls nextval on an Oracle sequence, but i noticed a strange behavior. The function is :

public class DAOImplementation{
    private static SessionFactory factory;
    private Session session;

    public BigDecimal getSequenceNextVal(){
        BigDecimal result = null;
        factory = HibernateUtil.getSessionFactory();
        session = factory.openSession();
        String sql = "select sequence_test.nextval from dual";
        Query query = session.createSQLQuery(sql);
        result = (BigDecimal) query.uniqueResult();
        session.close();
        return result;        
    }
}

When I print in console the value returned by the above function, I can see the correct next value. But, when I run on DB "select sequence_test.currval from dual" the value is not corresponding to the one in the console. If I reconnect to the Oracle DB from PL/SQL Developer and run the "select sequence_test.nextval from dual", the result is incremented by 2(i guess once by the java function and once more by the query executed manually).

Can you please help me to understand this situation?

Upvotes: 2

Views: 1478

Answers (1)

StuPointerException
StuPointerException

Reputation: 7267

sequence.currval is linked to your database session and is not actually the current value of the sequence in the sense that you're referring. Essentially currval will return the last value generated by nextval for a given session.

This is because the sequence is likely being changed by multiple sessions so the idea of a session independent current value rarely makes sense.

The name of this property is certainly confusing though...

Upvotes: 2

Related Questions