HQL:使用面向对象的HQL查询语言

Query接口
1.不可省略的from
String hql="from Student";
//创建Query实例
Query query = Session.createQuery(hql);
//执行HQL调用list(),返回List集合
List<Student> studentList = query.list();
2.select
//别名的使用
String hql="select s.name from Student as s";//as可省略
//创建Query实例
Query query = Session.createQuery(hql);
//默认返回List<Obejct>
List<Obejct> list = query.list();


String hql="select s.name,s.sex from Student as s";//as可省略
//创建Query实例
Query query = Session.createQuery(hql);
//默认返回List<Obejct[]>
List<Obejct> list = query.list();


//指定返回查询结果形式
String hql1="select new list(s.name,s.sex) from Student as s";
String hql2="select new map(t.name,t.sex) from Teacher as t";

Query query1 = Session.createQuery(hql1);
Query query2 = Session.createQuery(hql2);

List<list> list = query1.list();
List<Map> map = query2.list();

//查看
for(List l:list){
    System.out.println("s.name"+l.get(0));
    System.out.println("s.sex"+l.get("1"));
}
for(Map m:map){
    System.out.println("t.name"+m.get("0"));
    System.out.println("t.sex"+m.get("1"));
}
for(Map m:map){
    System.out.println("t.name"+m.get("name"));
    System.out.println("t.sex"+m.get("sex"));
}
//使用distinct关键字
String hql="select distinct s.sex from Student"
3.where
比较
String hql=" from Student s where s.sex='male'";
String hql=" from Student s where s.age<20";
String hql=" from Student s where s.sex=null";
String hql=" from Student s where s.sex is null";
范围
String hql=" from Student s where s.age in (20,40)";
字符串匹配
String hql=" from Student s where s.name like '_小_'";
String hql=" from Student s where s.name like '李%'";
逻辑and,or,not
String hql=" from Student s where s.age in (20,40) and s.name like '李%'";
集合运算
//is [not] empty---对应SQL中exists
String hql=" from Course c where c.teacher is not empty";
//member of---对应SQL中in
查询单个对象
//uniqueResult
String hql=" from Student s where s.id='101'";
//创建Query实例
Query query = Session.createQuery(hql);
//查询结果
Student student =(Student)query.uniqueResult();
4.order by
//升序asc,降序desc
String hql=" from Student s order by s.age asc,s.name desc";




评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值