簡體   English   中英

在 JPQL Native Query 中將查詢作為查詢參數傳遞

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

我試圖在另一個 JPQL 本機查詢中將查詢作為字符串參數傳遞。

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

所以結果查詢將類似於下面的查詢,它返回一個值

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

但我得到的回報只是:query參數的字符串,而不是執行完整查詢的結果。

  1. 為自定義存儲庫創建接口SomeRepositoryCustom
public interface SomeRepositoryCustom {

    BigDecimal getTotal(String sql);

}
  1. 創建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. 使用SomeRepositoryCustom擴展您的SomeRepositoryCustom
@Repository
public interface SomeRepository extends JpaRepository, SomeRepositoryCustom {

}

運行查詢

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM