2012-09-16 40 views
0

我的域有一個類別實體,它本身具有雙重關係。每個類別都可以有父母和子女。與父母/子女關係加載子實體JPA

@Entity 
public class Category implements DomainObject { 

    private Long id; 
    private Integer version; 
    private String name; 
    private Category parent; 
    private Set<Category> children; 

    @Override 
    @Id 
    @GeneratedValue 
    public final Long getId() { 
     return id; 
    } 

    @Version 
    public Integer getVersion() { 
     return version; 
    } 

    public void setVersion(Integer version) { 
     this.version = version; 
    } 

    public void setId(Long id) { 
     this.id = id; 
    } 

    @Column(unique=true, nullable=false) 
    public String getName() { 
     return name; 
    } 

    public void setName(String name) { 
     this.name = name; 
    } 

    @ManyToOne 
    public Category getParent() { 
     return parent; 
    } 

    public void setParent(Category parent) { 
     this.parent = parent; 
    } 

    @OneToMany 
    @JoinColumn(name = "parent_id") 
    public Set<Category> getChildren() { 
     return children; 
    } 

    public void setChildren(Set<Category> children) { 
     this.children = children; 
    } 
} 

我創建了以下查詢以獲取其「直接」(1級)子級的「根」類別。

select distinct c from Category c left join fetch c.children where c.parent is null order by c.name 

這實際上有效。我的問題是:爲什麼我需要getChildren()上的「JoinColumn」註解來實現這個功能,並且爲什麼我不能只做一個「foin fetch」查詢,而沒有「distinct」?如果我刪除「不同」我得到一個乘法。對於父代的每個子代,整個父代都被複制到結果集中。

有沒有更好的方法來做到這一點?它只是感覺...有點蹩腳。

+0

要明確一點,你不希望父母被抓到孩子? – siebz0r

+0

是的,我有。分類表實際上有多個父母。我有'編程','數據庫'和'管理'類別。這些都是根類別,它們是一個空父域。他們都有孩子(PHP,C#,用於編程的Python等)。我需要所有根類別與他們的孩子。這就是爲什麼我將'where c.parent is null'條件包含進去的原因。 – Julius

回答

0

在JPA中,您需要在加入OneToMany時設置不同的名稱,否則它將返回重複項。 這是必填項。

JPA規範要求這樣做,但它是一個奇怪的默認值,但涉及數據庫連接中發生的情況。