7

私はjpaクエリを使用していますが、適切な解決策を見つけることができます。あなたが私を助けてくれることを願っています。私のモデルの説明を始めます。会社に属するリソースがあります。同社には多くの支店があります。リソースには、いくつかのリソース所有権構成が関連付けられています。リソースの所有権は、どのブランチがリソースを使用できるか、およびこの構成が有効な期間を記述します。ただし、ブランチが指定されていない場合、リソースは会社のすべてのブランチで使用できます。

これがモデルです。ゲッターとセッターは省略

@Entity
public class Resource extends ActivableAbstractModel{

    /**
     * the serial version uid
     */
    private static final long serialVersionUID = -8568230011058859716L;

    public Resource() {
        this.ownerShipConfigurations = new ArrayList<>();
    }

    @Column(length=30)
    private String name;

    private String description;         

    @ManyToOne(cascade = {}, fetch = FetchType.LAZY, targetEntity=Company.class)
    @ForeignKey(name = "FK_company_resource")
    @JoinColumn(nullable = false)
    private Company company;



    @OneToMany(cascade={CascadeType.ALL}, orphanRemoval=true, mappedBy="resource")
    private List<ResourceOwnerShipConfiguration> ownerShipConfigurations;

}

実在物

@Entity
public class ResourceOwnerShipConfiguration extends AbstractModel{

    /**
     * the serial version uid
     */
    private static final long serialVersionUID = -4560593105136625002L;

    @Embedded
    private Period period;

    @ManyToOne(targetEntity=Company.class)
    private Company company;

    @ManyToMany(targetEntity=Branch.class)
    private List<Branch> branches;

    @ManyToOne
    private Resource resource;  
}

Branch Model と Company Model で重要なことは、どちらにも ID があることです。

これが私のクエリです:

@Query("select R from Resource R join R.ownerShipConfigurations oc join oc.branches b  where R.active = true and R.company.id = :companyId and (oc.branches IS EMPTY or  b.id = :branchId)")

私がしたいこと?会社に属し (companyId を使用)、特定のブランチ (branchId を使用) で使用できるすべてのリソースが必要です。ただし、リソースにブランチのリストがない場合 ( ResourceOwnerShipConfiguration で定義) を返す必要があります。

それが明確であることを願っています。

そのクエリを使用すると、リストとブランチを持たないリソースを取得できません。特定のブランチが関連付けられているものだけです。

前もって感謝します。

4

1 に答える 1

8

LEFT JOIN を使用する必要があります。

select R from Resource R join R.ownerShipConfigurations oc left join oc.branches b  where R.active = true and R.company.id = :companyId and (b.id is null or  b.id = :branchId)

http://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Querying/JPQL#LEFT_JOINを参照して ください

于 2012-04-24T13:46:43.483 に答える