簡體   English   中英

hibernate OneToMany 條件返回重復項

[英]hibernate OneToMany criteria returns duplicates

我有一個由以下映射的關聯:

@Entity
public class Parent
{
...
    @Id
    @Column(name = "parent_id")
    private Long id;

    @OneToMany(mappedBy = "parent")
    @OrderBy("id")
    private List<Child> children;
...
}

@Entity
public class Child
{
...
    @Id
    @Column(name = "child_id")
    private Long id;

    @ManyToOne
    @NotFound(action = NotFoundAction.IGNORE)
    @JoinColumn(name = "parent_id")
    private Parent parent;

    @Column
    private Boolean enabled;
...
}

我想使用標准Child來返回包含一個或多個具有屬性enabled=false的子實體的所有Parent實體的列表。 我不希望查詢過濾映射的children

例如,給定以下內容:

Parent A
    - Child A enabled=true
    - Child B enabled=false

Parent B
    - Child A enabled=false
    - Child B enabled=false

Parent C
    - Child A enabled=true
    - Child B enabled=true

查詢應返回以下內容:

Parent A
    - Child A enabled=true
    - Child B enabled=false

Parent B
    - Child A enabled=false
    - Child B enabled=false

到目前為止,我正在使用以下 Criteria 查詢:

Criteria crit = session.createCriteria(Parent.class);
crit.createCriteria("children").add(Restrictions.eq("enabled", false));
List<Parent> result = crit.list();
return result;

然而,它返回相當於

Parent A
    - Child A enabled=true
    - Child B enabled=false

Parent B
    - Child A enabled=false
    - Child B enabled=false

Parent B
    - Child A enabled=false
    - Child B enabled=false

即,它為每個enabled=false的子元素返回單個父記錄(填充了子集合)

有誰知道在這種情況下如何只返回唯一的父元素?

建議贊賞,p。

您需要添加一個distinct ,例如

criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

應該適用於你的情況

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM