Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting first row of table by criteria query

How can I get the first row of a table by using criteria or HQL query?

Table creation script

   CREATE TABLE MonthlySubscriber(MSISDN bigint(20) 
   NOT NULL, MonthOfYear int(11) NOT NULL, 
   PRIMARY KEY (MSISDN)); 
like image 215
Nikhil Mishra Avatar asked Jul 24 '13 05:07

Nikhil Mishra


People also ask

How do I get my first record in HQL?

There is no database independant way to express the FirstResult/MaxResult semantic in SQL. So there is no way you can do it via HQL. setFirstResult/setMaxResults will be translated into LIMIT x,y for MySQL Dialect. But the sql for other databases is totally different (e.g. "fetch first x rows only" for DB2).

What is root in criteria query?

For a particular CriteriaQuery object, the root entity of the query, from which all navigation originates, is called the query root. It is similar to the FROM clause in a JPQL query. Create the query root by calling the from method on the CriteriaQuery instance.

What is CriteriaQuery?

CriteriaQuery instance is used to create a query object. This query object's attributes will be modified with the details of the query. CriteriaQuery. from method is called to set the query root.

Is Criteria API deprecated?

The Criteria API allows us to build up a criteria query object programmatically, where we can apply different kinds of filtration rules and logical conditions. Since Hibernate 5.2, the Hibernate Criteria API is deprecated, and new development is focused on the JPA Criteria API.


1 Answers

Yes you can do that with setMaxResults & setFirstResult in criteria

Sample Code

Criteria queryCriteria = session.createCriteria(MonthlySubscriber.class);
queryCriteria.setFirstResult(0);
queryCriteria.setMaxResults(1);
monthlySubscriberList = queryCriteria .list();
like image 140
Jubin Patel Avatar answered Oct 20 '22 19:10

Jubin Patel