Criteria查询API 不需要写查询语句,比较适应单表查询
public void fun1(){
Session session = HibernateUtils.openSession();
Transaction tx = session.beginTransaction();
Criteria criteria = session.createCriteria(Customer.class);
List<Customer> list = criteria.list();//查询所有的Customer对象
tx.commit();
session.close();
}
1.Criteria普通条件查询
Criteria criteria = session.createCriteria(Customer.class);
criteria.add(Restrictions.eq("cust_id", 1l));
Customer c = (Customer) criteria.uniqueResult();
2.Criteria分页查询&升序查询
Criteria criteria = session.createCriteria(Customer.class);
criteria.setFirstResult(1);
criteria.setMaxResults(2);
criteria.addOrder(Order.asc("cust_id"));//升序查询
List<Customer> list = criteria.list();
3.Criteria查询总行数
Criteria criteria = session.createCriteria(Customer.class);
criteria.setProjection(Projections.rowCount());
Long count = (Long) criteria.uniqueResult();