对HQL常用检索方法的一些总结

该博客主要为日后查看关于HQL查询方法提供便利而写。

HQL查询有投影查询,条件查询,指定别名,动态实例和分页。由于后三种使用不熟我就不重点回顾,所以本文重点说前两种。

代码红色部分为查询具体代码。

1.投影查询:

目的是为了只通过查询部分属性来查询对象,从而节省查询性能。

查询方法是使用关键字select,并在其后加上需要查询的属性,然后就是from关键字和实体类名。

下面举例说明,在HQLTest类中,编写portionQueryTest()方法,只查询customer表中的name和age信息,代码如下所示。

@Test
public void portionQueryTest(){
Configurtion config=new Configuration().configure();
SessionFactory sessionFactory=config.buildSessionFactory();
Session session=sessionFactory.openSesssion();
Transaction t=session.beginTransaction();
String hql="select c.name,c.age from Customer as c";
Query query=session.createQuery(hql);
List<objest[]>list=query.list();
Iterator iter=list.iterator();
while(iter.hasNext()){
Objectp[] obj=(Object[])iter.next();
System.out.println(obj[0]+""+obj[1]);
}
t.commit();
session.close();
sessionFactory.close();
}
}

2.条件查询

目的是为了通过查询指定条件来查询对象。

查询方法有两种,一是按参数位置查询,二是用参数名字查询。

下面举例说明,先用参数位置查询,在HQLTest类中,编写portionQueryTest1()方法,模糊查询姓名为jo的人的信息,代码如下所示。


@Test
public void portionQueryTest(){
Configurtion config=new Configuration().configure();
SessionFactory sessionFactory=config.buildSessionFactory();
Session session=sessionFactory.openSesssion();
Transaction t=session.beginTransaction();
String hql="from Customer where name like ?";
Query query=session.createQuery(hql);
query.setString(0,%jo%");
List<Customer>cs=query.list();
for(Customer c: cs){
System.out.println(c);
}
t.commit();
session.close();
sessionFactory.close();
}
}

接着是用参数名字进行查询,在HQLTest类中,编写portionQueryTest2()方法,查询id为1的人信息,代码如下所示。

@Test
public void portionQueryTest(){
Configurtion config=new Configuration().configure();
SessionFactory sessionFactory=config.buildSessionFactory();
Session session=sessionFactory.openSesssion();
Transaction t=session.beginTransaction();
String hql="from Customer where id=:id";
Query query=session.createQuery(hql);
query.setparameter("id",1);
List<Customer>cs=query.list();
for(Customer c: cs){
System.out.println(c);
}
t.commit();
session.close();
sessionFactory.close();
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值