Criteria.uniqueResult()方法使查询持久性对象的单个实例变得更加容易。如果找不到持久性,则此方法将返回一个null值。
package org.nhooo.example.hibernate.criteria; import org.hibernate.Criteria; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.criterion.Restrictions; import org.nhooo.example.hibernate.model.Genre; public class UniqueResultExample { public static Session getSession() throws HibernateException { String cfg = "hibernate.cfg.xml"; SessionFactory sessionFactory = new Configuration().configure(cfg) .buildSessionFactory(); return sessionFactory.openSession(); } public static void main(String[] args) { try (Session session = getSession()) { Criteria criteria = session.createCriteria(Genre.class) .add(Restrictions.eq("id", 1L)); //返回单个实例的便捷方法 //查询;如果查询未返回结果,则返回null。 Object result = criteria.uniqueResult(); if (result != null) { Genre genre = (Genre) result; System.out.println("Genre = " + genre.getName()); } } } }