此示例演示了HibernateRestriction.in准则的使用。此限制将基于为bean的特定属性定义的参数集合来查询某些记录。
package org.nhooo.example.hibernate.criteria;
import org.hibernate.SessionFactory;
import org.hibernate.Session;
import org.hibernate.HibernateException;
import org.hibernate.Criteria;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Restrictions;
import org.nhooo.example.hibernate.model.Genre;
import java.util.List;
public class RestrictionInDemo {
public static Session getSession() throws HibernateException {
String cfg = "hibernate.cfg.xml";
SessionFactory sessionFactory = new Configuration().configure(cfg)
.buildSessionFactory();
return sessionFactory.openSession();
}
@SuppressWarnings("unchecked")
public static void main(String[] args) {
try (Session session = getSession()) {
// 创建一个Criteria并为该属性添加一个in约束
//ID。受限制的类型将返回ID为1、2、3的流派
// 和4。
Criteria criteria = session.createCriteria(Genre.class)
.add(Restrictions.in("id", 1L, 2L, 3L, 4L));
List<Genre> result = criteria.list();
for (Genre genre : result) {
System.out.println(genre);
}
}
}
}