Pergunta

I'm working with a jpa query and i can find a proper solution. I hope you can help me. I will start describing my model. I have a Resource which belongs to a company. The company has many Branches. The resource has associated a couple of resource ownership configuration. A resource ownership describe which branches can use the resource and a period of time in which this configuration is valid. But, if no branches are indicated the resource can be used by all the branches of the company.

here is the model. Getters and setters are omitted

@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

@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;  
}

What is important about Branch Model and Company Model is that both has a Id.

Here is my query:

@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)")

What i want to do? I want all the resources that belong to a company ( using companyId) and can be used by a particular branch (using branchId). But if the resource does not has a list of branches (defined in ResourceOwnerShipConfiguration ) must be returned.

Hope it is clear.

Using that query i can´t retrieve resources that does not have a list a branches. Just the ones which has the particular branch associated.

Thanks in advance.

Foi útil?

Solução

You need to use a 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)

See, http://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Querying/JPQL#LEFT_JOIN

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top