Can we get single object from hql query?

26,426

Solution 1

You can use query.getSingleResult()

Solution 2

You can use query.setMaxResults(1);

Solution 3

You can get the object at index 0 in the list:

List l = query.list() 
if (l.size()>0) {
  return l.get(0)
}

Solution 4

I don't think persitence should be mixed with business logic.

What about returning Optional from the persitence layer and whether result is present/absent do something in higher level?

In persistance layer something like:

return query.list() .stream() .findFirst()

This, according to docs, will return first result or empty optional if the collection was empty.

And then:

Optional<Bus> optionalBus = repository.find(busId, busStatus);
if (optionalBus.isPresent()) {
    something here
} else {
    something else
}
Share:
26,426
Raghu
Author by

Raghu

I am a Software Engineer in a star-up software firm. I love to program. Specially in JAVA. Currently working in ITS(Intelligent Transport System). It tracks the vehicles.

Updated on November 30, 2020

Comments

  • Raghu
    Raghu over 3 years

    I am writing a select query in hql , my task is to activate the bus. First I will get a messege from client as busId#busStatus, so first I look for this perticular busId is active or inactive So I have to write select query but in hibernate query.list() returns list. Here I think list is unnecessary , a single object is enough .

    Here is my code ,

        String hql="from BusDetailBean where Busid= :busId and bus_status=:busStatus";
            Query query = session.createQuery(hql);
            query.setParameter("busId", busId);
            query.setParameter("busStatus", busStatus);
    
            List<BusDetailBean> busDetails=(List<BusDetailBean>)query.list(); 
           if(busDetails.isEmpty())
            {
                 //my other stuff
            }
             else
             {
    
                //bus ativation stuff
             }
    

    My question is the select query returns only one object if list is not empty I have to use for loop in else part. So how can I optimise this code. can anyone help me in this.