代码之家  ›  专栏  ›  技术社区  ›  Tim Reddy

休眠条件-返回具有子记录的父记录

  •  3
  • Tim Reddy  · 技术社区  · 16 年前

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

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

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

    3 回复  |  直到 16 年前
        1
  •  7
  •   axtavt    16 年前

    Restrictions.isNotEmpty() 标准:

    List<A> r = s.createCriteria(A.class)
        .add(Restrictions.or(
            Restrictions.isNotEmpty("a1"), 
            Restrictions.isNotEmpty("a2"))).list();
    
        2
  •  0
  •   Stefan Steinegger    16 年前

    有一个 example in Ayende's Blog . 我现在没有时间解决这个问题。

        3
  •  -1
  •   Jamie LaMorgese    16 年前

    /*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)