How to return a single result object from hibernate query?

后端 未结 3 1078
悲&欢浪女
悲&欢浪女 2020-12-20 11:22

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         


        
相关标签:
3条回答
  • 2020-12-20 11:50

    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.

    0 讨论(0)
  • 2020-12-20 11:55

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

    0 讨论(0)
  • 2020-12-20 11:58

    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;
    
    0 讨论(0)
提交回复
热议问题