Hibernate Criteria - 返回具有子记录的父记录

时间:2010-07-07 14:30:42

标签: java sql hibernate

所有

我可能过度分析了这个问题,但是......

给定具有两个一对多关系“A1”和“A2”的表“A”,返回表“A”中在表“A1”或“A2”中具有至少一个子记录的所有记录。 ..

我不一定有兴趣知道孩子数据是什么,而是我只有孩子数据。

谢谢!

3 个答案:

答案 0 :(得分:7)

您需要Restrictions.isNotEmpty()条件:

List<A> r = s.createCriteria(A.class)
    .add(Restrictions.or(
        Restrictions.isNotEmpty("a1"), 
        Restrictions.isNotEmpty("a2"))).list();

答案 1 :(得分:0)

你需要一个子查询,使用DetachedCriteria:

有一个example in Ayende's Blog。我目前没有时间来解决这个问题。

答案 2 :(得分:-1)

我认为这个例子会对你有所帮助。它是用t-sql编写的,但应该很容易遵循你正在使用的平台。

/*Create data structures*/
CREATE TABLE Parent (  
  ParentId      INT         NOT NULL    PRIMARY KEY  
  , ParentName  VARCHAR(50) NOT NULL)

CREATE TABLE ChildA (  
  ChildAId      INT         NOT NULL    PRIMARY KEY  
  , ParentId    INT         NOT NULL    CONSTRAINT FK_ChildA_Parent FOREIGN KEY REFERENCES Parent(ParentId)  
  , ChildAName  VARCHAR(50) NOT NULL)

CREATE TABLE ChildB (  
  ChildBId      INT         NOT NULL    PRIMARY KEY  
  , ParentId    INT         NOT NULL    CONSTRAINT FK_ChildB_Parent FOREIGN KEY REFERENCES Parent(ParentId)  
  , ChildBName  VARCHAR(50) NOT NULL)

/* Insert four parents */  
INSERT INTO Parent VALUES (1,'A')  
INSERT INTO Parent VALUES (2,'B')  
INSERT INTO Parent VALUES (3,'C')  
INSERT INTO Parent VALUES (4,'D')  

/* Insert two children for A */  
INSERT INTO ChildA VALUES (1,1,'a')  
INSERT INTO ChildB VALUES (1,1,'a')

/* Insert one child for B */  
INSERT INTO ChildA VALUES (2,2,'b')

/* Insert one child for C */  
INSERT INTO ChildB VALUES (2,3,'c')

/* This select stmt returns A with children in both child tables, B with a child in ChildA, and C with a child in ChildB, but no D. */   
SELECT  *  
FROM    Parent p  
WHERE   EXISTS (select 1 from ChildA a where p.ParentId = a.ParentId)  
OR      EXISTS (select 1 from ChildB b where p.ParentId = b.ParentId)  
相关问题