Wednesday, June 30, 2010

Are u sure about Oracle ROWNUM ?

http://www.oracle.com/technology/oramag/oracle/06-sep/o56asktom.html

A simple implementation with JPA  on oracle dbms

    /*
     I had to make some improvements in query with oracle bec.of performance of the default jpa implementation.
     */
    public User[] getUsersInPage (int startIndex, int stopIndex) throws Exception {

        EntityManager em = createEntityManager ();
        List ret = new ArrayList();
        try {
            if (isOracle()){
                Query selectQuery = em.createNativeQuery ("SELECT * FROM (select a.*,rownum rnum from (select * from provisioning_subsys.VIP_USERS) a where ROWNUM <= " +
                    stopIndex + ") where rnum >=" + startIndex + "", User.class);
                ret = (List) selectQuery.getResultList ();
            }else{
                String qry = "select u from User u";
                Query selectQuery = em.createQuery (qry);
                selectQuery.setMaxResults (stopIndex - startIndex);
                selectQuery.setFirstResult (startIndex);
                ret = (List) selectQuery.getResultList ();
            }
        } finally {
            em.close ();
        }

        return getUserArrayFromList (ret);
    }

    private boolean isOracle () {
        if (emf instanceof EntityManagerFactoryImpl) {
            Properties jpaProperties = ((EntityManagerFactoryImpl) emf).getProperties ();
            String dbms = (String) jpaProperties.get ("Platform");
            if (dbms.indexOf ("Oracle") != -1) {
                return true;
            } else return false;
        }
        return false;
    }

No comments:

Post a Comment