简体   繁体   English

在 JPQL Native Query 中将查询作为查询参数传递

[英]Passing a query as a query parameter in JPQL Native Query

I'm trying to pass a query as a string parameter in another JPQL native query.我试图在另一个 JPQL 本机查询中将查询作为字符串参数传递。

@Query(value = "SELECT (:query)", nativeQuery = true)
BigDecimal getTotal(@Param("query") String query);

So the resulting query would be something like the query below that returns me a value所以结果查询将类似于下面的查询,它返回一个值

SELECT (50 * (SELECT COUNT(*) FROM SOMETABLE))

but what I'm getting in return is only the string of :query parameter and not the result of the executed complete query.但我得到的回报只是:query参数的字符串,而不是执行完整查询的结果。

  1. Create an interface for a custom repository SomeRepositoryCustom为自定义存储库创建接口SomeRepositoryCustom
public interface SomeRepositoryCustom {

    BigDecimal getTotal(String sql);

}
  1. Create an implementation of SomeRepositoryCustom创建SomeRepositoryCustom的实现
@Repository
class SomesRepositoryCustomImpl implements SomeRepositoryCustom {

    private JdbcTemplate template;

    @Autowired
    public SomesRepositoryCustomImpl(JdbcTemplate template) {
        this.template = template;
    }

    @Override
    public BigDecimal getTotal(String sql) {
        return template.queryForObject(sql, BigDecimal.class);
    }

}
  1. Extend your JpaRepository with SomeRepositoryCustom使用SomeRepositoryCustom扩展您的SomeRepositoryCustom
@Repository
public interface SomeRepository extends JpaRepository, SomeRepositoryCustom {

}

to run a query运行查询

someRepository.getTotal("SELECT (50 * (SELECT COUNT(*) FROM SOMETABLE))");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM