Phoenix
Phoenix

Reputation: 8923

How to return a single result object from hibernate query?

Does a query execution always have to return a list ? How do I replace the code below if I am sure it will only return a single object ?

@Override
    public List<DocInfo> findAllByDocId(String docId)
    {
        Query q = getCurrentSession().createQuery("from DocInfo item where item.id = :docId");
        q.setString("docId", docId);
        List<DocInfo> docInfoList = q.list();
        return docInfoList;
    }

Upvotes: 19

Views: 35117

Answers (3)

Guido
Guido

Reputation: 47665

You can use Query#uniqueResult() with Hibernate if I am not wrong. I think that is what you are looking for. In this case, you have to handle the NonUniqueResultException in your code if there is more than one row returned from your query.

Upvotes: 22

Steve Ebersole
Steve Ebersole

Reputation: 9443

If you are loading by id (pk), as it appears you are here, you really should use Session.load/Session.get instead.

Upvotes: 0

Bharat Sinha
Bharat Sinha

Reputation: 14363

You can use

query.getSingleResult();

when you are absolutely sure that query would return only one row and I am talking about

import javax.persistence.Query;

Upvotes: 6

Related Questions