我正在使用 jpa 查询,我可以找到合适的解决方案。我希望你能帮助我。我将开始描述我的模型。我有一个属于一家公司的资源。公司下设多家分公司。该资源关联了几个资源所有权配置。资源所有权描述了哪些分支可以使用该资源以及此配置有效的时间段。但是,如果没有指定分支机构,则该资源可以被公司的所有分支机构使用。
这是模型。省略了 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
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 中定义),则必须返回。
希望很清楚。
使用该查询我无法检索没有分支列表的资源。只是与特定分支相关联的那些。
提前致谢。