【发布时间】:2021-07-18 08:34:27
【问题描述】:
我有以下实体:
@AllArgsConstructor
@EqualsAndHashCode(of = {"name"})
@Data
@NoArgsConstructor
@Entity
@Table(schema = "eat")
public class Pizza {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator="pizza_id_seq")
private Integer id;
@NotNull
private String name;
@NotNull
@Positive
private Double cost;
@ManyToMany
@JoinTable(schema = "eat",
name = "pizza_ingredient",
inverseJoinColumns = { @JoinColumn(name = "ingredient_id") })
private Set<Ingredient> ingredients;
}
@AllArgsConstructor
@EqualsAndHashCode(of = {"name"})
@Data
@NoArgsConstructor
@Entity
@Table(schema = "eat")
public class Ingredient {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator="ingredient_id_seq")
private Integer id;
@NotNull
@Size(min=1, max=64)
private String name;
}
我正在使用 QueryDSL (4.2.2) 提供的 JPASQLQuery 对象在 PostgreSQL 中创建一些本机查询:
public JPASQLQuery<T> getJPASQLQuery() {
return new JPASQLQuery<>(
entityManager,
PostgreSQLTemplates.builder().printSchema().build()
);
}
问题在于尝试使用join函数,例如:
QIngredient ingredient = QIngredient.ingredient;
QPizza pizza = QPizza.pizza;
StringPath ingredientPath = Expressions.stringPath("ingredient");
StringPath pizzaPath = Expressions.stringPath("pizza");
NumberPath<Double> costPath = Expressions.numberPath(Double.class, "cost");
Expression rowNumber = SQLExpressions.rowNumber().over().partitionBy(ingredientPath).orderBy(costPath.desc()).as("rnk");
JPASQLQuery subQuery = getJPASQLQuery()
.select(ingredient.name.as(ingredientPath), pizza.name.as(pizzaPath), pizza.cost.as(costPath), rowNumber)
.from(pizza)
// The error is in next innerJoin
.innerJoin((SubQueryExpression<?>) pizza.ingredients, ingredient)
.where(ingredient.name.in(ingredientNames));
如果我保留当前的innerJoin((SubQueryExpression<?>) pizza.ingredients, ingredient) 我会收到:
class com.querydsl.core.types.dsl.SetPath cannot be cast to class com.querydsl.core.types.SubQueryExpression
我无法删除当前的(SubQueryExpression<?>),因为innerJoin 不接受SetPath作为参数。
另一方面,如下:
.from(pizza)
.innerJoin(ingredient)
由于pizza_ingredient 未包含在生成的查询中,因此不起作用。
如何在JPASQLQuery 中使用innerJoin 与上述多对多关系?
【问题讨论】: