I’m trying to pass a query as a string parameter in another JPQL native query.
JavaScript
x
@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
JavaScript
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.
Advertisement
Answer
- Create an interface for a custom repository
SomeRepositoryCustom
JavaScript
public interface SomeRepositoryCustom {
BigDecimal getTotal(String sql);
}
- Create an implementation of
SomeRepositoryCustom
JavaScript
@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);
}
}
- Extend your JpaRepository with
SomeRepositoryCustom
JavaScript
@Repository
public interface SomeRepository extends JpaRepository, SomeRepositoryCustom {
}
to run a query
JavaScript
someRepository.getTotal("SELECT (50 * (SELECT COUNT(*) FROM SOMETABLE))");