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