Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we get single object from hql query?

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.

like image 892
Raghu Avatar asked Nov 20 '25 06:11

Raghu


2 Answers

You can use query.getSingleResult()

like image 85
CodZilla Avatar answered Nov 22 '25 21:11

CodZilla


You can use query.setMaxResults(1);

like image 38
Kalaiarasan Manimaran Avatar answered Nov 22 '25 20:11

Kalaiarasan Manimaran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!