hibernate中的查询

HQL

  • 查询所有
String hql = "from Customer";
Query query = session.createQuery(hql);
List list = query.list();
  • 条件查询
String hql = "from Customer where cust_id=:cust_id";
Query query = session.createQuery(hql);
query.setParameter("cust_id", 2l);
Object uniqueResult = query.uniqueResult();
  • 分页查询
String hql = "from Customer";
Query query = session.createQuery(hql);
query.setFirstResult(0);
query.setMaxResults(2);
List list = query.list();

Criteria

  • 查询所有
Criteria criteria = session.createCriteria(Customer.class);
List list = criteria.list();
  • 条件查询
Criteria criteria = session.createCriteria(Customer.class);
criteria.add(Restrictions.idEq(2l));
Object uniqueResult = criteria.uniqueResult();
  • 分页查询
Criteria criteria = session.createCriteria(Customer.class);
criteria.setFirstResult(0);
criteria.setMaxResults(2);
List list = criteria.list();
  • 查询总记录
Criteria criteria = session.createCriteria(Customer.class);
criteria.setProjection(Projections.rowCount());
Object uniqueResult = criteria.uniqueResult();

原生SQL

你可能感兴趣的:(hibernate中的查询)