如何在@Query中添加动态位置?

时间:2018-12-14 13:08:00

标签: spring-boot spring-data-jpa repository jpql

我需要基于我的过滤器对象添加where条件。如果过滤器对象中的某些值为null,则不必添加此参数的where条件。

如何在哪里添加动态内容?

示例:

FilterObject{
  name: "Teste";
  age: null;
}

@Query(value="SELECT id FROM user WHERE name = FilterObject.name", nativeQuery = true)
public List<User> getUsers(???)

其他示例:

FilterObject{
  name: "Teste";
  age: 12;
}

@Query(value="SELECT id FROM user WHERE name = FilterObject.name AND age = FilterObject.age", nativeQuery = true)
public List<User> getUsers(???)

这是一个高级示例。不是正确的代码。但是...是理解我的问题所必需的

如果我的过滤器参数为null,则该参数不会在我的where中使用

我将Spring Boot与Spring Data JPA一起使用,而我的查询则保留在我的存储库中。

我的原始请求:

    @Query(value = " SELECT "
        + " solicitacao.nm_orgao AS nmOrgao, "
        + " solicitacao.ds_ano_exercicio AS exercicio, "
        + " solicitacao.nm_organismo AS nmOrganismo, "
        + " dadosBancarios.valor AS valor, "
        + " dadosBancarios.valor * dadosBancarios.vl_taxa_cambio AS valorReais, "
        + " dadosFinanceiros.vl_dotacao_disponivel AS vlDotacaoDisponivel, "
        + " solicitacao.id_solicitacao AS codigoPagamento "
        + " solicitacao.tp_solicitacao_status AS  idFase, "
        + " organismo.id_orgao AS idOrgao, "
        + " solicitacao.id_organismo AS idOrganismo, "
        + " pagamentos.id_status_pagamento AS statusPagamento "
        + " FROM "
        + " tbs_solicitacao solicitacao "
        + " JOIN tbs_dados_bancarios dadosBancarios ON solicitacao.id_solicitacao = dadosBancarios.id_solicitacao "
        + " JOIN tbs_dados_financeiros dadosFinanceiros ON dadosFinanceiros.id_solicitacao = solicitacao.id_solicitacao "
        + " JOIN tbs_organismo organismo ON organismo.id_organismo = solicitacao.id_organismo "
        + " JOIN tbs_pagamentos pagamentos ON dadosFinanceiros.id_dados_financeiros = pagamentos.id_dados_financeiros ",nativeQuery = true)
List<Object[]> getRelatoriosProgramacao();

1 个答案:

答案 0 :(得分:0)

您可以使用Spring Data JPA规范:

https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#specifications

您只需实现toPredicate方法:

 Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder);

通过这种方法,您将获得root,查询和CriteriaBuilder,以在谓词处创建Criteria API。

findAll之类的事件方法具有规范。