hibernate的criterion.Restrictions条件查询例子
Hibernate的条件查询主要通过Criteria类、Criterion、Restrictions来完成,作用是:Criteria:执行一次查询。Criterion:设置一个条件查询。Restrictions:产生条件查询的工具类。。
下面例子是通过criterion.Restrictions进行条件查询,取得ajava的ID为1,3,5,7的用户名。
,
package org.ajava.example.hibernate.criteria;import org.hibernate.SessionFactory;import org.hibernate.Session;import org.hibernate.HibernateException;import org.hibernate.Criteria;import org.hibernate.criterion.Restrictions;import org.hibernate.cfg.AnnotationConfiguration;import org.ajava.example.hibernate.model.Genre;import java.util.List;public class RestrictionInDemo { private static final SessionFactory sessionFactory; static { try { sessionFactory = new AnnotationConfiguration(). configure("hibernate.cfg.xml"). buildSessionFactory(); } catch (Throwable ex) { throw new ExceptionInInitializerError(ex); } } public static Session getSession() throws HibernateException { return sessionFactory.openSession(); } @SuppressWarnings("unchecked") public static void main(String[] args) { final Session session = getSession(); try { Criteria criteria = session.createCriteria(Genre.class) .add(Restrictions.in("id", new Long[] {1, 3, 5, 7})); List<Genre> result = criteria.list(); for (Genre genre : result) { System.out.println("Ajava user:"+genre.getId() + "; " + genre.getName()); } } finally { session.close(); } }}