[英]Querydsl: how to downcast a join entity?
I'm looking for a way to make a join on a one-to-many relation where the many-side is defined through inheritance and the right part of the join is restricted to a specific subclass (downcast).我正在寻找一种在一对多关系上进行联接的方法,其中多方是通过继承定义的,并且联接的正确部分仅限于特定的子类(向下转换)。
Say I have the entities below (example taken from here ):假设我有以下实体(示例取自此处):
@Entity
public class Project {
@Id
@GeneratedValue
private long id;
private String name;
@OneToMany(cascade = CascadeType.ALL)
private List<Employee> employees;
.............
}
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@Entity
@DiscriminatorColumn(name = "EMP_TYPE")
public class Employee {
@Id
@GeneratedValue
private long id;
private String name;
.............
}
@Entity
@DiscriminatorValue("F")
public class FullTimeEmployee extends Employee {
private int annualSalary;
.............
}
@Entity
@DiscriminatorValue("P")
public class PartTimeEmployee extends Employee {
private int weeklySalary;
.............
}
@Entity
@DiscriminatorValue("C")
public class ContractEmployee extends Employee {
private int hourlyRate;
.............
}
I can easily build join queries that involve properties defined in the superclass Employee
, like:我可以轻松构建涉及超类
Employee
定义的属性的连接查询,例如:
JPAQuery query = ...
QProject project = new QProject("p");
QEmployee employee = new QEmployee("e");
query.join(project.employees, employee);
query.where(employee.name.startsWith("A"));
But if I want to access a property of subclass, say FullTimeEmployee.annualSalary
, and hence restrict the join to that sub-type, how do I do that?但是,如果我想访问子类的属性,例如
FullTimeEmployee.annualSalary
,从而将连接限制为该子类型,我该怎么做?
How do I build the the equivalent of following JPQL:如何构建等效于以下 JPQL 的内容:
SELECT DISTINCT p FROM Project p JOIN TREAT(p.employees AS FullTimeEmployee) e WHERE e.annualSalary > 100000
You can do it like this:你可以这样做:
EntityManager em = ...;
QProject p = QProject.project;
QFullTimeEmployee e = QFullTimeEmployee.fullTimeEmployee;
List<FullTimeEmployee> emps = new JPAQuery<>(em)
.select(p)
.distinct()
.from(p)
.innerJoin(p.employees, e._super)
.where(e.annualSalary.gt(100000))
.fetch();
See also this post on the Querydsl forum: https://groups.google.com/d/msg/querydsl/4G_ea_mQJgY/JKD5lRamAQAJ另请参阅 Querydsl 论坛上的此帖子: https ://groups.google.com/d/msg/querydsl/4G_ea_mQJgY/JKD5lRamAQAJ
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.