Home > hibernate, java > Next Sequence Value Using Hibernate Entity Manager

Next Sequence Value Using Hibernate Entity Manager

To retrieve the next value of an Orcale sequence using the Hibernate Entity Manager first create a result set mapping.

@SqlResultSetMapping(name = "NextSequenceVal", columns = { @ColumnResult(name = "NEXTVAL") })

The mapping can go anywhere, I like to put it on the entity it is most closely associated with.
Then in your DAO.

    public Long getNextElecTransUniqueId()
    {
        Query query = entityManager.createNativeQuery("SELECT MY_SEQUENCE.NEXTVAL from Dual",
                "NextSequenceVal");
        // Workaround for
        // http://opensource.atlassian.com/projects/hibernate/browse/EJB-434
        // which breaks query.getSingleResult()
        return ((BigDecimal) query.getResultList().get(0)).longValue();

    }

This example is written for Hibernate 3.3.2, Hibernate Entity Manager 3.4.0, Oracle 10g.

Note: in Entity Manager 3.4.0 if you use query.getSingleResult() you will get the exception:
Exception: org.hibernate.exception.SQLGrammarException: could not execute query^M
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:90)^M
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)^M
at org.hibernate.loader.Loader.doList(Loader.java:2235)^M
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2129)^M
at org.hibernate.loader.Loader.list(Loader.java:2124)^M
at org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:312)^M
at org.hibernate.impl.SessionImpl.listCustomQuery(SessionImpl.java:1723)^M
at org.hibernate.impl.AbstractSessionImpl.list(AbstractSessionImpl.java:165)^M
at org.hibernate.impl.SQLQueryImpl.list(SQLQueryImpl.java:175)^M
at org.hibernate.ejb.QueryImpl.getSingleResult(QueryImpl.java:88)^M
Caused by: java.sql.SQLException: ORA-02287: sequence number not allowed here

Categories: hibernate, java
  1. No comments yet.
  1. No trackbacks yet.