在嵌套DTO中查询结果

时间:2018-04-16 23:33:11

标签: spring-data

Spring Data中不允许在JPQL查询中嵌套DTO吗? :

@Query("SELECT new test.customresult.CategoryCounter(c.name, " 
        + "new test.customresult.CarResult(COUNT(e.category), e.category)"
        + "FROM error e JOIN e.car c  "
        + "GROUP BY c.name,e.category")
List<CategoryCounter>countErrors();

因为,在尝试使用上述JPQL查询时出现以下错误消息:

Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: , near line 1, 

我想从JPQL查询中返回这样一个JSON文件:

[{
        "Car 1": 
        [{
                "count": 1,
                "category": "A"
            }, {
                "count": 2,
                "category": "B"
            }, {
                "count": 0,
                "category": "C"
            }, {
                "count": 0,
                "category": "D"
            }
        ]

    }, {
        "Car 2": 
        [{
                "count": 0,
                "category": "A"
            }, {
                "count": 0,
                "category": "B"
            }, {
                "count": 4,
                "category": "C"
            }, {
                "count": 5,
                "category": "D"
            }
        ]

    }
]

有一个汽车表和一个错误表,其中包含汽车表的类别和外键。

我想使用嵌套的DTO来表示所需的输出:

“包装”DTO

public class CategoryCounter {

    private String name;
    private CarResult carResult ;

    public CategoryCounter (String name, CarResult carResult ) {

        this.name= name;
        this.carResult = carResult ;
    }


    public CarResult getCarResult () {
        return carResult ;
    }

    public void setCarResult(CarResult carResult ) {
        this.carResult = carResult ;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name= name;
    }

}

和“嵌套”DTO:

public class CarResult {


    private Long count;
    private String category;

    public CarResult (Long count, String category) {

        this.count = count;
        this.category= category;
    }


    public Long getCount() {
        return count;
    }

    public void setCount(Long count) {
        this.count = count;
    }
    public String getCategory() {
        return category;
    }
    public void setCategory(String category) {
        this.category= category;
    }
}

1 个答案:

答案 0 :(得分:0)

我不确定这是否可能是问题...但是你的FROM子句会在)之后立即开始:

+ "new test.customresult.CarResult(COUNT(e.category), e.category)"
+ "FROM error e JOIN e.car c  "

e.category)FROM相同,所以在该部分放置一个空格再试一次......

+ "new test.customresult.CarResult(COUNT(e.category), e.category)"
+ " FROM error e JOIN e.car c  "

问题是错误(由:org.hibernate.hql.internal.ast.QuerySyntaxException引起)是语法错误