Use of the Hibernate uniqueResult Method

Source: Internet
Author: User

If you write code before, you can't write the login part. When obtaining a user, only one user instance may be returned, or the value is null. Previously, the following methods were used for implementation.
Public User get (String id ){
Session session = HibernateUtil. getSessionFactory (). openSession ();
String hql = "from User u where u. id =? ";
List list = session. createQuery (hql). setString (0, id). list ();
If (list. size () = 1 ){
Return (User) list. get (0 );
} Else {
Return null;
}
}
[Java]
Public User get (String id ){
Session session = HibernateUtil. getSessionFactory (). openSession ();
String hql = "from User u where u. id =? ";
List list = session. createQuery (hql). setString (0, id). list ();
If (list. size () = 1 ){
Return (User) list. get (0 );
} Else {
Return null;
}
}
Yesterday I re-read the reference manual of hibernate and found that the query interface provides a better way to get an instance. When the returned instance explicitly only has one or is null.
UniqueResult
Public Object uniqueResult () throws HibernateException return: a single instance or null throw: When the returned instance is greater than one, the corresponding method of using NonUniqueResultException is as follows:

[Java] www.2cto.com
Public User get (String id ){
Session session = HibernateUtil. getSessionFactory (). openSession ();
String hql = "from User u where u. id =? ";
Return (User) session. createQuery (hql). setString (0, id). uniqueResult ();
 
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.