多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
## 两种批量查询的方式 1. Query : 使用这种方式查询,又被称作HQL查询. 2. Criteria : 使用这种方式查询,又被称做QBC查询. ## HQL查询 ### 条件查 ~~~ //条件查询,类似SQL语句,但是不是SQL.from的是持久化类,不是表名. Query query = session.createQuery("from Customer where cust_name like ?"); query.setParameter(0,"%j%"); List<Customer> list = query.list(); for (Customer c : list) { System.out.println(c); } ~~~ ### 分页查 ~~~ Query query = session.createQuery("from Customer"); //起始数据 query.setFirstResult(2); //设置条数 query.setMaxResults(5); List<Customer> list = query.list(); for (Customer c : list) { System.out.println(c); } ~~~ ### 单列查 ~~~ //cust_id是属性,不是字段名 Query query = session.createQuery("select cust_id from Customer"); List<Object> list = query.list(); //返回的是Object for (Object o : list) { System.out.println(o); } ~~~ ### 多列查 ~~~ Query query = session.createQuery("select cust_id,cust_name from Customer"); List<Object[]> list = query.list(); //list每一项是一个数组 for (Object[] o : list) { System.out.println(Arrays.toString(o)); } ~~~ ### 投影查询 两个条件: 1. 查多少个字段持久化类构造函数就需要写多少个属性. 2. 语法书写: select new Customer(cust_id,cust_name) from Customer; ~~~ //投影查询 Query query = session.createQuery("select new Customer(cust_id,cust_name) from Customer"); List<Customer> list = query.list(); for (Customer c : list) { System.out.println(c); } ~~~ ### 排序查 ~~~ Query query = session.createQuery("select new Customer(cust_id,cust_name) from Customer order by cust_id desc"); List<Customer> list = query.list(); for (Customer c : list) { System.out.println(c); } ~~~ ### 聚合查询 ~~~ Query query = session.createQuery("select count(*) from Customer"); Object o = query.uniqueResult(); System.out.println(o); ~~~ ## QBC查询