1

I need to convert this query to hql to use it my code :

SELECT DISTINCT
    certificate_id , last_scan 
FROM 
    bcs_certificate_instance 
ORDER BY 
    last_scan 
LIMIT 5 ; 

Who can help please?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Hana_CH
  • 105
  • 1
  • 12

1 Answers1

1
select distinct bci.certificate_id , bci.last_scan 
from bcs_certificate_instance bci
order by last_scan asc;

And for limit you have to use setMaxResults() funtion on query object before executing it.

A code snippet for this would look like:

Query query = em.createQuery(“select distinct bci.certificate_id , bci.last_scan 
from bcs_certificate_instance bci
order by last_scan asc;”);
query.setMaxResults(10);
List resultData = query.getResultList();

Thats it. So that is how you limit the number of records returned by a query in HQL.

Example with @Query annotation:

public interface PersonDao extends EntityDao<Person, Long> {

    @Query("select p from Person p where p.age between ?1 and ?2")

QueryResult<Person> findAllByAge(int minAge, int maxAge);

}    

Once you have obtained a QueryResult, you can apply further options and restrictions to the query:

List<Person> result = personDao.findAllByAge(18, 65)

.sortAsc(Person_.lastName)

.sortDesc(Person_.age).

.firstResult(10)

.maxResults(10)

.getResultList();

}  
Osama Khalid
  • 307
  • 4
  • 14
  • I can't use the set max result option because i am using the @Query annotation .. so i have to set the max value in the query – Hana_CH Dec 26 '19 at 10:24
  • I have added another example with @Query annotation. See if this is helpful to you. Thanks – Osama Khalid Dec 26 '19 at 16:08