【问题标题】:JPA left outer join: is empty or conditionJPA左外连接:为空或条件
【发布时间】:2012-05-04 13:32:49
【问题描述】:

我正在使用 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;  
}

分支机构模型和公司模型的重要之处在于两者都有一个 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 中定义),则必须返回。

希望清楚。

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

提前致谢。

【问题讨论】:

    标签: jpa spring-data-jpa


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2018-08-02
      • 1970-01-01
      • 2019-06-17
      • 1970-01-01
      • 1970-01-01
      • 2013-01-18
      • 2010-11-11
      • 2020-01-12
      • 1970-01-01
      相关资源
      最近更新 更多