List<Customer> list = session.createQuery("from Customer").list();
for (Customer customer : list) {
System.out.println(customer);
}
2.3 查询使用别名
// 使用别名
// 别名as可以省略
/* List<Customer> list =
session.createQuery("from Customer c").list();
System.out.println(list);*/
// 使用别名:带参数
/*List<Customer> list = session
.createQuery("from Customer as c where c.cname = ?")
.setString(0, "小沈").list();
System.out.println(list);*/
// 不支持 select * from Customer写法.可以写成 select 别名 from Customer as 别名;
List<Customer> list = session.createQuery("select c from Customer c").list();
System.out.println(list);
2.4 排序
List<Customer> list = session.createQuery(
"from Customer c order by c.id desc").list();
for (Customer customer : list) {
System.out.println(customer);
}
2.5 分页查询
Query query = session.createQuery("from Order");
query.setFirstResult(20);
query.setMaxResults(10);
List<Order> list = query.list();
for (Order order : list) {
System.out.println(order);
}
// 1.使用?号方式绑定
/*Query query = session.createQuery("from Customer where cname = ?");
query.setString(0, "小沈");
List<Customer> list = query.list();
System.out.println(list);*/
/*Query query = session.createQuery("from Customer where cname = ? and cid =?");
query.setString(0, "小沈");
query.setInteger(1,3);
List<Customer> list = query.list();
System.out.println(list);*/
// 2.使用名称的方式绑定
Query query = session.createQuery("from Customer
where cname=:name and cid=:id");
query.setString("name", "小沈");
query.setInteger("id", 3);
List<Customer> list = query.list();
System.out.println(list);
// 3.绑定实体
List<Order> list = session
.createQuery("from Order o where o.customer = ?")
.setEntity(0, customer).list();
for (Order order : list) {
System.out.println(order);
}
2.8 投影操作
// 查询客户的名称:
List<Object> list = session.createQuery(
"select c.cname from Customer c").list(); System.out.println(list);
List<Object[]> list = session.createQuery(
"select c.cid,c.cname from Customer c").list();
for (Object[] objects : list){
System.out.println(Arrays.toString(objects));
}
List<Customer> list = session.createQuery(
"select new Customer(cname) from Customer").list();
System.out.println(list);
2.9 模糊查询
Query query = session.createQuery("
from Customer where cname like ?");
query.setParameter(0, "小%");
List<Customer> list = query.list();
System.out.println(list);
2.10 SQL多表查询
连接:
交叉连接:
select * from A,B;
内连接:查询的是两个表的交集!
select * from A inner join B on A.字段 = B.字段;
隐式内连接:
select * from A,B where A.字段 = B.字段;
外连接:
左外连接:
select * from A left outer join B on A.字段 = B.字段;
右外连接:
select * from A right outer join B on A.字段 = B.字段;
List<Object[]> list = session.createSQLQuery("select * from
customer").list();
for (Object[] objects : list) {
System.out.println(Arrays.toString(objects));
}
List<Customer> list = session.createSQLQuery("select * from
customer").addEntity(Customer.class).list();
for (Customer customer : list) {
System.out.println(customer);
}