私のドメインには、それ自体に双方向の関係があるカテゴリエンティティがあります。各カテゴリには、親と子を含めることができます。
@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」アノテーションが必要なのはなぜですか。また、「distinct」なしで「foinfetch」クエリを作成できないのはなぜですか。「distinct」を削除すると、乗算が発生します。親の子ごとに、親全体が結果セットにコピーされます。
これを行うためのより良い方法はありますか?それはただ感じます...少しくだらない。