1、hql参数化查询,不明确值类型的用setParameter方法;明确查询结果为一条记录的用uniqueResult方法查询

注意,参数化查询中方法setString 或 setParameter如果使用索引方式赋值,索引值从0开始,区别JDBC

public void func1(){
Session session=HibernateUtils.getSession();
session.beginTransaction();
String hql="from Customer where name=:name";
Query query=session.createQuery(hql);
//传参数
//query.setString("name", "Tom");或者下面
  query.setParameter("name", "Tom");
//List<Customer>cusList=query.list();
//如果明确知道查询结果就一条记录,则用下面方法
  Customer customer=(Customer) query.uniqueResult();
session.getTransaction().commit();
session.close();
//System.out.println(cusList.get(0).getName());
  System.out.println(customer.getName());
}

2、hql分页查询

public void func2(){
Session session=HibernateUtils.getSession();
session.beginTransaction();
Query query=session.createQuery("from Customer");
//设置起始行索引
query.setFirstResult(1);
//设置最多返回记录数量
query.setMaxResults(2);
List<Customer>cusList=query.list();
session.getTransaction().commit();
session.close();
System.out.println(cusList.get(0).getName()+","+cusList.get(0).getId());
System.out.println(cusList.get(1).getName()+","+cusList.get(1).getId()); }

3、qbc分页查询

public void func1(){
Session session=HibernateUtils.getSession();
session.beginTransaction(); Criteria criteria=session.createCriteria(Customer.class);
//设置起始行索引
criteria.setFirstResult(1);
//设置最多返回记录数量
criteria.setMaxResults(2);
List<Customer>cusList=criteria.list(); System.out.println(cusList.get(0).getName()+","+cusList.get(0).getId());
System.out.println(cusList.get(1).getName()+","+cusList.get(1).getId());
session.getTransaction().commit();
session.close();
}

4、qbc条件查询

public void func2(){
Session session=HibernateUtils.getSession();
session.beginTransaction();
Criteria criteria=session.createCriteria(Customer.class);
//设置查询条件,name等于Tom的
criteria.add(Restrictions.eq("name", "Tom"));
//已明确查询结果为一条记录
Customer customer=(Customer) criteria.uniqueResult(); session.getTransaction().commit();
session.close();
System.out.println(customer.getName());
}

5、qbc复杂条件查询

public void func3(){
Session session=HibernateUtils.getSession();
session.beginTransaction();
Criteria criteria=session.createCriteria(Customer.class);
//设置查询条件,name等于Tom的
criteria.add(Restrictions.eq("name", "Jack")).add(Restrictions.or(Restrictions.gt("id", 3), Restrictions.eq("city", "上海")));
List<Customer> cusList=criteria.list(); session.getTransaction().commit();
session.close();
for (int i = 0; i < cusList.size(); i++) {
System.out.println(cusList.get(i).getId());
}
}
05-11 15:21