在我的Repository界面中,我有2个类似的聚合查询,它们只在group by column上有所不同,
@Query(value = "select table1.a1, sum(table2.b), sum(table2.c) from table2"
+ " join table1 on table2.table1_id = table1.id group by table1.a1", nativeQuery = true)
public List<FooDTO> getAggregateSumWithGroupByA1();
@Query(value = "select table1.a2, sum(table2.b), sum(table2.c) from table2"
+ " join table1 on table2.table1_id = table1.id group by table1.a2", nativeQuery = true)
public List<FooDTO> getAggregateSumWithGroupByA2();
我不想重复这两个查询的公共部分,而是想实现这样的东西:
String myGroupByQuery = "select table1.%s, sum(table2.b), sum(table2.c) from table2"
+ " join table1 on table2.table1_id = table1.id group by table1.%s";
@Query(value = StringFormat.format(myGroupByQuery, "a1"), nativeQuery = true)
public List<FooDTO> getAggregateSumWithGroupByA1();
@Query(value = StringFormat.format(myGroupByQuery, "a2"), nativeQuery = true)
public List<FooDTO> getAggregateSumWithGroupByA2();
当然,上面的代码显示错误:The value for annotation attribute Query.value must be a constant expression
有什么方法可以做到这一点,或者有任何其他建议来实现类似的东西吗?谢谢。
到处找,但没有找到满足我要求的解决方案。
1条答案
按热度按时间4xrmg8kj1#
您可以尝试使用Spring Dynamic JPA库(https://github.com/joutvhu/spring-dynamic-jpa)。不要使用两个方法,只保留一个,并将“group by”条件作为String参数传递。