java 如何在Sping Boot JPA存储库中重用长但相似的原生查询的公共部分?

ujv3wf0j  于 2023-03-28  发布在  Java
关注(0)|答案(1)|浏览(118)

在我的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有什么方法可以做到这一点,或者有任何其他建议来实现类似的东西吗?谢谢。
到处找,但没有找到满足我要求的解决方案。

4xrmg8kj

4xrmg8kj1#

您可以尝试使用Spring Dynamic JPA库(https://github.com/joutvhu/spring-dynamic-jpa)。不要使用两个方法,只保留一个,并将“group by”条件作为String参数传递。

相关问题