Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use the Query.uniqueResult () method in Hibernate

Shulou Source: shulou.com Published: 2022-06-03 11:01:59 11月15日 Update

This article will explain in detail how to use the Query.uniqueResult () method in Hibernate. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

Reread the hibernate reference manual and find that the query interface provides a better way to get instances when it is clear that there is only one instance or it is null. PublicObjectuniqueResult () throwsHibernateException returns: a single instance or null throws: when the returned instance is larger than one, the corresponding usage of throwing NonUniqueResultException is as follows:

Query.uniqueResult () in Hibernate

If multiple values are thrown incorrectly

If there is only one value, an object is returned

If there is no value, return null

PublicObjectuniqueResult () throwsHibernateException returns: single instance or null throw: throw NonUniqueResultException when the returned instance is greater than one

When it is determined that there is only one instance returned or is null, then uniqueResult () is the best choice, using the following methods:

PublicUserget (Stringid) {

Sessionsession=HibernateUtil.getSessionFactory () .openSession ()

Stringhql= "fromUseruwhereu.id=?"

Return (User) session.createQuery (hql) .setString (0memid) .uniqueResult ()

}

Use of the HibernateuniqueResult method

In the past, when writing code, it was inevitable to write the login part. When getting user, it is possible to return only one user instance, or null. It was previously implemented using the following methods.

PublicUserget (Stringid) {

Sessionsession=HibernateUtil.getSessionFactory () .openSession ()

Stringhql= "fromUseruwhereu.id=?"

Listlist=session.createQuery (hql) .setString (0recom id) .list ()

If (list.size ()) = = 1) {

Return (User) list.get (0)

} else {

Returnnull

}

}

[java]

PublicUserget (Stringid) {

Sessionsession=HibernateUtil.getSessionFactory () .openSession ()

This is the end of the article on "how to use the Query.uniqueResult () method in Hibernate". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Tags: Example method time only article usage single more reference good practical code content multiple manual interface article best knowledge part Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Linux Shulou Technology Shulou Tech Info Docker NVidia