如何从Hibernate查询中返回单个结果对象? [英] How to return a single result object from hibernate query?

查看:963
本文介绍了如何从Hibernate查询中返回单个结果对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查询执行是否总是返回一个列表?

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;
    }


推荐答案

您可以使用查询#uniqueResult()与休眠,如果我没有错。我认为这就是你要找的。在这种情况下,如果查询返回多行,则必须在代码中处理 NonUniqueResultException

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.

这篇关于如何从Hibernate查询中返回单个结果对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆