我正在尝试使用Spring Data JPA Specification来实现此SQL查询的等效项:
SELECT * FROM product WHERE category_id IN (....)
此查询涉及的两个实体具有OneToMany
和ManyToOne
关系:
产品实体:
@Data
@NoArgsConstructor
@Entity
@Table(name = "PRODUCT")
public class ProductEntity extends AbstractAuditableEntity {
// skipped other properties for simplicity sake
@ManyToOne
private CategoryEntity categoryEntity;
}
CategoryEntity:
@Entity
@Table(name = "PRODUCT_CATEGORY")
@Data
public class CategoryEntity extends AbstractBaseEntity {
// skipped other properties for simplicity sake
@OneToMany(mappedBy = "categoryEntity")
private List<ProductEntity> productEntities;
}
我的JPA规范查询可以编译并运行,没有任何错误,但是不返回任何结果:规范定义:
public static Specification<ProductEntity> inCategories(List<Long> categories) {
return (root, query, builder) -> {
if (categories != null && !categories.isEmpty()) {
final Path<CategoryEntity> category = root.get("categoryEntity");
return category.get("id").in(categories);
} else {
// always-true predicate, means that no filtering would be applied
return builder.and();
}
};
}
客户代码:
Page<ProductEntity> productEntityPage = productRepository.findAll(Specification
.where(ProductSpecifications.inCategories(filterCriteria.getCategories()))
, pageRequest);
为什么不起作用?使用SQL语句查询数据库时会得到结果,因此我的JPA规范查询或实体映射一定存在问题。
我想念什么?
我想你应该在这里使用join
Join<Product, CategoryEntity> categoryJoin = root.join("categoryEntity");
return categoryJoin.get("id").in(categories);
代替
Path<CategoryEntity> category = root.get("categoryEntity");
return category.get("id").in(categories);
因为root.get("categoryEntity");
不会提供任何信息,因为表中不存在此类路径(product.categoryEntity.id
)product
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句