JPA左外连接:为空或条件

时间:2012-04-23 22:09:13

标签: jpa spring-data-jpa

我正在使用jpa查询,我可以找到一个合适的解决方案。我希望你能帮助我。我将开始描述我的模型。我有一个属于公司的资源。该公司有许多分支机构。资源已关联了一些资源所有权配置。资源所有权描述了哪些分支可以使用资源以及此配置有效的时间段。但是,如果没有指示分支,则该资源可以被公司的所有分支使用。

这是模型。 getters和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;  

}

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中定义),则必须返回。

希望很清楚。

使用该查询,我无法检索没有列表分支的资源。只是具有特定分支的那些。

提前致谢。

1 个答案:

答案 0 :(得分:7)

您需要使用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

相关问题