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.
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.
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.
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.
You can accomplish this using setFirstResult and setMaxResults.
session.createCriteria(Foo.class)
.setFirstResult(0)
.setMaxResults(1);
you can set rownum or limits in property of query;
Query q =entityManager.createQuery("select * from employee_table");
q.setFirstResult(0);
q.setMaxResults(30);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With