---
title: "Hibernate查询"
author: "Diablogs"
date: "2010-04-07T13:31:26Z"
tags: ["C", "C#", "C++", "Go", "Hibernate"]
categories: ["企业架构"]
slug: "hibernate"
draft: false
lastmod: "2010-04-07T13:31:26Z"
id: 636176
url: "https://diablogs.iteye.com/blog/636176"
---

本文通过实例分析讲解几个Hibernate查询技巧，包括数据库的创建，xml文件的配置，以及每个问题的问及答，希望大家喜欢！ Create DataBase SHOPPING; go use SHOPPING; go /\*==============================================================\*/ /* Table: CATEGORIES \*/ /\*==============================================================\*/ create table CATEGORIES ( CATEGORY\_ID bigint identity, CATEGORY\_NAME varchar(100) not null, CATEGORY\_DESCN varchar(500) null, constraint PK\_CATEGORIES primary key (CATEGORY\_ID) ) go /\*==============================================================\*/ /* Table: PRODUCTS \*/ /\*==============================================================\*/ create table PRODUCTS ( PRODUCT\_NO varchar(10) not null, CATEGORY\_ID bigint not null, PRODUCT\_NAME varchar(300) not null, PRODUCT\_PRICE float not null, PHOTO\_PATH varchar(100) null, PRODUCT\_DESCN varchar(2000) null, constraint PK\_PRODUCTS primary key (PRODUCT\_NO) ) go /\*==============================================================\*/ /* Table: PRODUCT\_SUPPLY \*/ /\*==============================================================\*/ create table PRODUCT\_SUPPLY ( SUPPLY\_NO varchar(10) null, PRODUCT\_NO varchar(10) null ) go /\*==============================================================\*/ /* Table: SUPPLIERS \*/ /\*==============================================================\*/ create table SUPPLIERS ( SUPPLY\_NO varchar(10) not null, SUPPLY\_NAME varchar(200) not null, SUPPLY\_DESCN varchar(400) null, constraint PK\_SUPPLIERS primary key (SUPPLY\_NO) ) go /\*==============================================================\*/ /* Create Relation \*/ /\*==============================================================\*/ alter table PRODUCTS add constraint FK\_PRODUCTS\_REFERENCE\_CATEGORI foreign key (CATEGORY\_ID) references CATEGORIES (CATEGORY\_ID) go alter table PRODUCT\_SUPPLY add constraint FK\_PRODUCT\_\_REFERENCE\_PRODUCTS foreign key (PRODUCT\_NO) references PRODUCTS (PRODUCT\_NO) go alter table PRODUCT\_SUPPLY add constraint FK\_PRODUCT\_\_REFERENCE\_SUPPLIER foreign key (SUPPLY\_NO) references SUPPLIERS (SUPPLY\_NO) go 创建数据库脚本的 PRODUCTS（产品表） 和 CATEGORIES(类别表)一对多 PRODUCT\_SUPPLY 为中间表 SUPPLIERS（供货商表） 和 PRODUCTS 为多对多的关系。 products 表 hbm.xml category 表 hbm.xml supply 表 hbm.xml

```
  
             
             
 
```

1， 添加一个的新商品名称为”Compaq 2620” 该商品属于“笔记本”类别 由当前所有的提供商提供货源 List list = session.createQuery("from Supply").list(); Category c = (Category) session.get(Category.class, new Long(1)); product.setCategory(c); product.setSupplys(new HashSet(list)); session.save(product); 2， 查询编号为” S0001”的提供商提供的所有商品 //通过隐式内连接导航 List list = session.createQuery("from Product p where p.supplys.supply\_no='S0001'").list(); 隐式内连接导航 要注意的一个问题是 从many端到 one 端 可以无限导航 但从one到many端只能导航一级 3,查询编号为”S0002”的提供商提供的所有商品所涉及的类别 session.createQuery("from Category c where c.productes.product\_no in (select p.product\_no from Product p where p.supplys.supply\_no='S0002' ) ").list(); 用到子查询 4，查询名称为”TCL SHE8533”的商品的每个提供商的编号、名称(部分属性查询) session.createQuery("select s.supply\_no,s.supply\_name from Supply s where s.products.product\_name='TCL SHE8533'").list(); //投影查询。 如果想将查询出来的 结果封装成对象 用 select new package.Temp(s.a,s.b...) from .... Temp提供相应的构造方法包含可选的字段注意带包名。 5， 查询多于3种商品的类别信息（使用size函数处理） session.createQuery("from Category s where s.productes.size&gt;3").list(); 注意其中的 size 表示的是 商品类别中产品数量多于3的类别。size用来处理集合中的大小 6，查询至少有一个商品的类别信息（使用exists处理） session.createQuery("from Category c where exists( from c.productes) ").list(); 7，查询可以提供某种商品的供应商信息（使用elements处理） session.createQuery("from Supply s where :product in elements(s.products) ")..setParameter("product", product).list(); product为 一个 对象 。 product in elements(s.products) 表示这个对象是否在这个集合中 8，使用本地SQL,显示所有商品的商品名、价格以及类别信息，并降序排列。 session.createSQLQuery("select p.PRODUCT\_NAME,p.PRODUCT\_PRICE ,c.* from PRODUCTS p ,CATEGORIES c where p.CATEGORY\_ID = c.CATEGORY\_ID order by p.PRODUCT\_PRICE desc") 的到的 集合中是个 Object\[]; 如果想返回对象 可以用命名sql并在配置文件中指定返回的对象类型。 9 分页查询 ：将商品按价格升序排列后，取第三页的记录，(每页显示2条记录) Query query = session.createQuery("from Product p order by p.product\_price ") .setFirstResult(2\*(3-1)) .setMaxResults(2); 10，查询所有类别的名字,及该类别包含的商品数量 (使用group by ,count函数) session.createQuery("select max(c.category\_name), count(p) from Category c inner join c.productes p group by c.category\_id ") 还有一种简单的方式就是 : "select c.category\_name, c.products.size from Category c " 11,批处理: 将某个类别下的商品修改为现有的另一个类别。 int count = session.createQuery("update Product p set p.category=:category where p.category.category\_id='1'") .setParameter("category",c ).executeUpdate(); c为加载的一个新的类别 12，往数据库中初始化3个名称相同的商品(其他字段自行设置)。要求：查询所有商品,如果多个商品的名称相同，则取其中任意一个完整的商品信息 hql = "from Prodcut pp where pp.product\_no in (select max(p.category\_id) from Product p group by p.product\_name") ; 注意后面的一个 小技巧。 由于group by 后只能包含 group by字段和聚合函数 所以如果我想区别的字段似乎不可能 。但我们不妨将你要取的那个字段也加个聚合函数min 或 max 这样就可以取出你要的 任意字段了。适应sql sql2000中不妨 在pubs 下运行 select max(title\_id) as 编号 ,count(type) as 数量, type from titles group by type 看看结果就知道了 虽然只 group by 了 type但还是可以得到title\_id 本文来自: IT知道网(http://www.itwis.com) 详细出处参考：http://www.itwis.com/html/java/hibernate/20080616/1757.html