16

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)); 
musicin3d
  • 1,028
  • 1
  • 12
  • 22
Nikhil Mishra
  • 397
  • 1
  • 6
  • 21

4 Answers4

31

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();
Jubin Patel
  • 1,959
  • 19
  • 38
4

you could do that like this:

Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
        String sql= "select b.wcd, a.optime from UseWaterRecord a, WellBasicInfo b where a.stcd=:a_stcd and b.stcd=:b_stcd ORDER BY a.optime desc";
        Query query = session.createQuery(sql);
        query.setString("a_stcd", "10100405");
        query.setString("b_stcd", "10100405");
        query.setFirstResult(0);
        query.setMaxResults(1);

        List wrwmList = query.list();
Huang
  • 51
  • 4
1
 Criteria queryCriteria = currentSession.createCriteria(Project.class);
 queryCriteria.setFirstResult(0);
 queryCriteria.setMaxResults(1);
 entity = (Project) queryCriteria.uniqueResult(); // Casting to the Entity class
-3
public Criteria setFirstResult(int firstResult)

This method takes an integer that represents the first row in your result set, starting with row 0. REFER

Ganesh Rengarajan
  • 2,006
  • 13
  • 26
  • 3
    `setFirstResult` use to get start row but it gives all rows from below that. for that must have to use `setMaxResults`. – Jubin Patel Jul 24 '13 at 05:24
  • 1
    @JubinPatel isn't `setFirstResult` explicit in conjunction with `setMaxResults`? – Dragon Apr 21 '16 at 14:42