如何将此SQL语句转换为HQL

时间:2018-12-31 00:47:20

标签: postgresql hibernate spring-boot hql

我得到以下SQL语句:

SELECT p.category_id, COUNT(p.id)
FROM products p
WHERE p.name ILIKE 'product%'
GROUP BY p.category_id

并且我想将其转换为该实体的HQL:

产品:

private Long id;

@NotNull
private String name;

@NotNull
private String description;

@NotNull
private String image;

@NotNull
private Double price;

@ManyToOne
private Category category;

我得到的是:

@Query("SELECT p.category.id, COUNT(p.id) " +
        "FROM Product p " +
        "WHERE p.name LIKE ?1 " +
        "GROUP BY p.category.id")
List<SearchDetail> findSearchDetailsByName(String phrase);

但是它给了我以下错误: https://pastebin.com/h4yBPc7d

2 个答案:

答案 0 :(得分:1)

尝试一下:

@Query("SELECT new com.cm.sb.SearchDetail(p.category.id as category, COUNT(p.id) as count)  " +
            "FROM Product p " +
            "WHERE p.name LIKE ?1 " +
            "GROUP BY p.category.id")
    List<SearchDetail> findSearchDetailsByName(String phrase);

如您所见,您必须在查询中指定SearchDetail的软件包。

Nb:我已经测试了该解决方案,并且可以正常工作:)

答案 1 :(得分:0)

我认为您可能只需要为查询中与SearchDetail pojo中的字段名称匹配的所选列提供别名:

@Query("SELECT p.category.id AS category, COUNT(p.id) AS count" +
    "FROM Product p " +
    "WHERE p.name LIKE ?1 " +
    "GROUP BY p.category.id")
List<SearchDetail> findSearchDetailsByName(String phrase);