2012-04-23 62 views
2

我正在使用jpa查詢,我可以找到適當的解決方案。我希望你能幫助我。我將開始描述我的模型。我有一個屬於公司的資源。該公司有許多分支機構。該資源已關聯了一些資源所有權配置。資源所有權描述哪些分支可以使用該資源以及該配置有效的一段時間。但是,如果沒有指定分支機構,則該公司的所有分支機構都可以使用該資源。JPA left outer join:爲空或條件

這裏是模型。 getter和setter省略

@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 公共類ResourceOwnerShipConfiguration擴展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; 

}

是什麼樣的店模式和公司模式重要的是,無論有一個編號。

這裏是我的查詢:

@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中定義)必須返回。

希望很清楚。

使用該查詢我無法檢索沒有分支的列表的資源。只有那些有特定分支關聯的人。

在此先感謝。

回答