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

匿名 (未验证) 提交于 2019-12-03 00:25:02

该博客主要为日后查看关于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(); } }

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!