---
title: "hibernate子查询"
author: "godlogin"
date: "2011-11-03T14:38:46Z"
tags: []
categories: ["编程语言"]
slug: "hibernate"
draft: false
lastmod: "2011-11-03T14:42:07Z"
id: 1233381
url: "https://godlogin.iteye.com/blog/1233381"
---

以前以为复杂的子查询只能用hql实现，今天高人指点，原来也可以用Criteria对象实现。

例如，查询a表中没有在b表出现的记录
SQL： select * from tableA a where not exists (select 1 from tableB b where b.id=a.id and b.name=**)

hibernate:

```java

DetachedCriteria dCriteria = DetachedCriteria.forClass(TableB.class, "b").setProjection(Property.forName("id")).add(Expression.and(Restrictions.eqProperty("a.id", "b.id"), Expression.eq("b.name", name)));
Session.CreateCriteria(TableA.class,"a").add(Subqueries.notExists(dCriteria)).List();
```