单表查询:
【基本查询】
String hql = “ from Customer" //Customer也可以写成完整类名,如果一个项目中有两个这样同名的类,要写完整类名
String hql = "select * from Costomer" //和上面一样
Query query = session.createQuery(hql)
Customer customer = query.uniqueResult()//获得一个对象
List<Customer> list = query.list()//获得一个对象列表
【条件查询】
String hql = “ from Customer where cust_id = 1"
Query query = session.createQuery(hql);
Customer customer = query.uniqueResult()
【条件查询 问号占位符】
String hql = “ from Customer where cust_id = ?"
Query query = session.createQuery(hql);
query.setParameter(0,1l) //占位符是从0开始
Customer customer = query.uniqueResult()
【条件查询 命名占位符】
String hql = “ from Customer where cust_id = :cust_id"
Query query = session.createQuery(hql);
query.setParameter("cust_id",1l) //不用知道这个占位符是第几个
Customer customer = query.uniqueResult()
【分页查询】
String hql = “ from Customer"
Query query = session.createQuery(hql);
query.setFirstResult(xx) //xx指的是从第几条开始查
query.setMaxResult(yy) //yy指的是查多少条
List<Customer> list = query.list()
【排序查询】
String hql = " from Customer order by cust_id desc "
【统计查询】
count:统计条数 sum:求某列所有值相加的和 avg:求某列所有值的平均数 max:求某列最大数 min:求某列最小数
String hql = "select count(*) from Customer"
Query query = session.createQuery(hql)
Number number = (Number) query.uniqueResult()
【投影查询】(查询对象的一个属性值)
String hql = "select cust_name from Customer"
Query query = session.createQuery(hql)
List<String> list = query.list()
【投影查询】(查询对象的多个属性值)
String hql = "select new Customer(user_id,user_name) from User"
Query query = session.createQuery(hql)
List list = query.list()
//这个查询的必要条件是User类中必须有且仅有user_id,user_name这两个属性的构造函数
多表查询:不常用
【内连接】
String hql = " from Customer c inner join c.linkMens "
Query query = session.createQuery(hql)
List<Object[]> list = query.list()//返回的是一个集合数组,每个数组中有两个对象
for(Object[] arr : list){}//返回值如下
【迫切内连接】
String hql = " from Customer c inner join fetch c.linkMens "
Query query = session.createQuery(hql)
List<Customer> list = query.list()
【左外连接】
String hql = " from Customer c left join c.linkMens "
Query query = session.createQuery(hql)
List<Object[]> list = query.list()//返回的是一个集合数组,每个数组中有两个对象
for(Object[] arr : list){}//返回值如下
【右外连接】
String hql = " from Customer c right join c.linkMens "
Query query = session.createQuery(hql)
List<Object[]> list = query.list()//返回的是一个集合数组,每个数组中有两个对象
for(Object[] arr : list){}//返回值如下