hibernate---session查询

时间:2021-09-07 13:09:44

一、hql语句查询(适合多表)

public class MyTest {
public static void main(String[] args) { //查询集合
Session session = SessionUtil.openSession();
String hql = "from Emp";
Query query = session.createQuery(hql);
@SuppressWarnings("unchecked")
List<Emp> list = query.list(); //带条件查询方法1
String hql2 = "from Emp where empno = ?";
Query query2 = session.createQuery(hql2);
query2.setInteger(0, 23);
Emp emp = (Emp) query2.uniqueResult(); //带条件查询方法2
String hql3 = "from Emp where empno = ?";
Query query3 = session.createQuery(hql3);
query3.setParameter(0, 23);
Emp emp2 = (Emp) query3.uniqueResult(); //带条件查询方法3(命名占位符)
String hql4 = "from Emp where empno = :xx";
Query query4 = session.createQuery(hql4);
query4.setParameter("xx", 23);
Emp emp3 = (Emp) query4.uniqueResult(); //分页查询
String hql5 = "from Emp";
Query query5 = session.createQuery(hql5);
query5.setFirstResult(0);
query5.setMaxResults(10);
@SuppressWarnings("unchecked")
List<Emp> list2 = query5.list(); System.out.println(list);
System.out.println(emp);
System.out.println(emp2);
System.out.println(emp3);
System.out.println(list2);
}
}

二、criteria查询(无语句查询,适合单表查询)

  

private static void run2() {
//查询集合
Session session = SessionUtil.openSession();
Criteria criteria = session.createCriteria(Emp.class);
List<Emp> list = criteria.list(); /*
* 带条件查询方法
* > gt
* < lt
* == eq
* != ne
*/
Criteria criteria2 = session.createCriteria(Emp.class);
criteria2.add(Restrictions.eq("empno", 23));
Emp emp = (Emp) criteria2.uniqueResult(); //分页查询
Criteria criteria3 = session.createCriteria(Emp.class);
criteria3.setFirstResult(0);
criteria3.setMaxResults(2);
List<Emp> list2 = criteria3.list(); System.out.println(list);
System.out.println(emp);
System.out.println(list2);
}

三、原生态sql语句查询

private static void run3() {
//集合查询
Session session = SessionUtil.openSession();
String sql = "select * from Emp";
SQLQuery sqlQuery = session.createSQLQuery(sql);
sqlQuery.addEntity(Emp.class);
List<Emp> list = sqlQuery.list(); //条件查询
String sql2 = "select * from emp where ename = ?";
SQLQuery sqlQuery2 = session.createSQLQuery(sql2);
// sqlQuery2.setParameter(0, "JAMES");
sqlQuery2.setString(0, "JAMES");
sqlQuery2.addEntity(Emp.class);
List<Emp> list2 = sqlQuery2.list(); //分页查询
//如果是mysql使用特有的limit
//如果是oracle使用原生态sql查询 System.out.println(list);
System.out.println(list2);
}