Raghu
Raghu

Reputation: 1324

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.

Upvotes: 3

Views: 30056

Answers (6)

avs
avs

Reputation: 45

For this type of problem, the out of the box solution in Hibernate is to use the uniqueResult() method in the Query class:

public Object uniqueResult()

From the Hibernate JavaDocs:

Convenience method to return a single instance that matches the query, or null if the query returns no results.

Returns: the single result or null

Throws:

  • NonUniqueResultException - if there is more than one matching result
  • HibernateException

Upvotes: 0

alexd
alexd

Reputation: 122

by using query.uniqueResult() you don't ensure that if you have many results , then you will get only one of them.

With uniqueResult() you place a guard/contraint at your result set to be aware that this query should always return a unique result.

Upvotes: 0

slnowak
slnowak

Reputation: 1919

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
}

Upvotes: 1

CodZilla
CodZilla

Reputation: 151

You can use query.getSingleResult()

Upvotes: 6

Kalaiarasan Manimaran
Kalaiarasan Manimaran

Reputation: 1658

You can use query.setMaxResults(1);

Upvotes: 2

Jens
Jens

Reputation: 69440

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

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

Upvotes: 1

Related Questions