To get a sequence nextval in oracle using Hibernate
public static BigDecimal getSequenceNextVal(String sequenceName) { return (BigDecimal)HibernateUtils.getSession().createSQLQuery("select "+sequenceName+".NEXTVAL as id from dual").addScalar("id").uniqueResult(); }where HibernateUtils is the following class
import java.util.ArrayList;
import java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import tn.cnss.referentiel.models.Assure; import tn.cnss.referentiel.models.Beneficiaire; public class HibernateUtils { private static final SessionFactory sessionFactory; static { try { StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build(); //Annotated classes to be scanned List<Class<?>> classes = new ArrayList<Class<?>>(); classes.add(YYYYYYYYYYYYY.class); classes.add(XXXXXXXXXXXXX.class); //Attach classes MetadataSources metadataSources = new MetadataSources(standardRegistry); for (Class<?> annotatedClass : classes) { metadataSources.addAnnotatedClass(annotatedClass); } sessionFactory = metadataSources.buildMetadata() .buildSessionFactory(); } catch (Throwable th) { System.err.println("Enitial SessionFactory creation failed" + th); throw new ExceptionInInitializerError(th); } } public static SessionFactory getSessionFactory() { return sessionFactory; } public static Session getSession() throws org.hibernate.HibernateException { SessionFactory sessionFactory = HibernateUtils.getSessionFactory(); Session sess = null; try { sess = sessionFactory.getCurrentSession(); } catch (org.hibernate.HibernateException he) { sess = sessionFactory.openSession(); } return sess; } }