Müs*_*sli 5 jpa spring-data-jpa
我正在使用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;
}
Run Code Online (Sandbox Code Playgroud)
@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;
Run Code Online (Sandbox Code Playgroud)
}
分支模型和公司模型的重要之处在于它们都具有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)")
Run Code Online (Sandbox Code Playgroud)
我想做的事?我想要所有属于公司的资源(使用companyId)并且可以由特定分支使用(使用branchId).但是,如果资源没有分支列表(在ResourceOwnerShipConfiguration中定义),则必须返回.
希望很清楚.
使用该查询,我无法检索没有列表分支的资源.只是具有特定分支的那些.
提前致谢.
你需要使用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)
Run Code Online (Sandbox Code Playgroud)
请参阅 http://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Querying/JPQL#LEFT_JOIN
| 归档时间: |
|
| 查看次数: |
16634 次 |
| 最近记录: |