Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resolve Oracle's 'rownum' pseudocolumn with JPA Criteria API?

I would like to get first row from database using JPA Criteria. I use JPA, Hibernate 4.2.7. In SQL, statement looks like:

SELECT * FROM houses WHERE rownum = 1;

My Java code to achive that looks like:

    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<House> query = builder.createQuery(House.class);
    Root<House> root = query.from(House.class);

    query.select(root).where(builder.equal(root.get("rownum"), 1));

    TypedQuery<House> tQuery = entityManager.createQuery(query); 
    House house = tQuery.getSingleResult();

But 'rownum' pseudocolumn cannot be resolved, I get exception:

 java.lang.IllegalArgumentException: Unable to resolve attribute [rownum] against path
at org.hibernate.ejb.criteria.path.AbstractPathImpl.unknownAttribute(AbstractPathImpl.java:120)
at org.hibernate.ejb.criteria.path.AbstractPathImpl.locateAttribute(AbstractPathImpl.java:229)
at org.hibernate.ejb.criteria.path.AbstractPathImpl.get(AbstractPathImpl.java:200)

Is is possible, and if so, how to get 'rownum' pseudocolumn with Criteria API? Thanks for any suggestions.

like image 435
gadon Avatar asked Jan 03 '14 20:01

gadon


People also ask

Why Rownum 1 is not working in Oracle?

in the case of where rownum = 1, the first row passes the test, is output and rownum goes to 2. No other row ever satisfies the predicate and rownum stays at 2 for the rest of the query. in the case of where rownum = 2, the first row is rownum 1, it fails.

How does Oracle assign ROWNUM?

For each row returned by a query, the ROWNUM pseudocolumn returns a number indicating the order in which Oracle selects the row from a table or set of joined rows. The first row selected has a ROWNUM of 1, the second has 2, and so on.

How to select ROWNUM in Oracle?

You can use ROWNUM to limit the number of rows returned by a query, as in this example: SELECT * FROM employees WHERE ROWNUM < 10; If an ORDER BY clause follows ROWNUM in the same query, then the rows will be reordered by the ORDER BY clause. The results can vary depending on the way the rows are accessed.


2 Answers

You can accomplish this using setFirstResult and setMaxResults.

session.createCriteria(Foo.class)
   .setFirstResult(0)
   .setMaxResults(1);
like image 146
bradleyfitz Avatar answered Sep 22 '22 04:09

bradleyfitz


you can set rownum or limits in property of query;

Query q =entityManager.createQuery("select * from employee_table");

q.setFirstResult(0);

q.setMaxResults(30);

like image 40
djavaphp Avatar answered Sep 21 '22 04:09

djavaphp