欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Hibernate查询

程序员文章站 2022-04-15 23:45:17
...
Hibernate的HQL语法;
HQL语法和SQL语法应用一致,区别在于SQL语句针对的是表名和列名,而HQL语句针对的是Po类名和属性名;
完整的HQL语句:select ... from ...where...group by...having...order by...asc/desc;
支持删除和修改;
--查询所有,可以省略select *
String hql = "from UserPO ";
Session session = HibernateSessionFactory.getSession();
Query query = session.createQuery(hql);
<em>//查询结果可以返回List,也可返回Iterator类型;
//List类型不支持延迟加载;
//Iterator类型支持延迟加载,底层执行的SQL语句N+1条
//也就是说第一句SQL语句从数据库中查询出id集合,再根据id查询每个po对象;</em>

List list = query.list();
for(int i = 0; i < list.size(); i++){
UserPO user = (UserPO)list.get(i);
System.out.println(user.getName());
}
Iterator iterator = query.iterate();
while(iterator.hasNext()){
UserPO user = (UserPO)iterator.next();
System.out.println(user.getName());
}
session.close();



--查询指定字段
String hql = "select name from UserPO ";
list.get(i)这时候返回的类型和name类型一致;
String hql = "select name,id from UserPO ";
list.get(i)这时候返回的类型是一个Object[];
<em>如果想让list.get(i)在返回时候自动将查询字段封装到po对象中,需要满足一下两个条件;
(1)、在po类中书写默认构造和特定构造,比如查询name和id,则构造这两个属性;
(2)、在HQL语句中"select new UserPo(name,id) from UserPO ";--告诉Hibernate用哪个构造方法.
使用配置查询;
Hibernate允许在Mapping映射的配置文件中定义HQL语句
< query name="findbyname">
< ![CDATA[from Customer c where c.name = :username]]>
< /query>
代码里面:
Query query = session.getNamedQuery("findbyname");
query.setString("username","tiger");
List list = query.list();
也可以配置sql语句
< sql-query name="newfind">
< ![CDATA[select * from Customer where name = :username]]>
< return alias="customer" class="com.ms.hibernate.Customer"/>
< sql-/query>
Query query = session.getNamedQuery("newfind");
query.setString("username","tiger");
List list = query.list();