0

Estou enfrentando um problema de conversão de dados para uma classe VO (ou DTO), ao realizar uma pesquisa em uma Stored Procedure, do banco Oracle, quando no repositório utilizo a anotação @Procedure do Spring JPA.

Obs: Consegui fazer com que o código funcione se ao invés de usar o Spring JPA utilizar o JDBC, criando uma nova interface e utilizando o EntityManager, mas não é o que eu gostaria.

Segue abaixo algumas informações do meu processo:

Stored Procedure

create or replace PROCEDURE "SP_SIMULAR_PROJECAO" 
(
  P_ID_METRICA_FREQ IN NUMBER 
, P_DATA_INICIO IN DATE 
, R_CURSOR OUT SYS_REFCURSOR 
) AS 
BEGIN

  
    OPEN r_cursor FOR
    SELECT 
      data,
      realizado,
      previsto,
      simulado,
      metrica_freq
    FROM
    *--Demais resto do código da Stored Procedure*
  
EXCEPTION
    WHEN OTHERS THEN
    DBMS_OUTPUT.put_line (DBMS_UTILITY.format_error_backtrace);
    raise;

END SP_SIMULAR_PROJECAO;

Classe VO (ou pode ser um DTO)

public class SimulacaoVO implements Serializable {

    /** Serial Version UID. */
    private static final long serialVersionUID = -9162758718909641984L;

    private LocalDateTime data;
    private Double realizado;
    private Double previsto;
    private Double simulado;
    private Long metricaFreq;

    public SimulacaoVO() {}

    public SimulacaoVO(LocalDateTime data, Double realizado, Double previsto, Double simulado, Long metricaFreq) {
        this.data = data;
        this.realizado = realizado;
        this.previsto = previsto;
        this.simulado = simulado;
        this.metricaFreq = metricaFreq;
    }

    *// getters e setters*
}

Entidade

@Entity
@Table(name = "VW_DASH_CAMADA_SERVIDORES")
@NamedStoredProcedureQueries({
        @NamedStoredProcedureQuery(name = "spSimularProjecao", procedureName = "sp_simular_projecao", resultSetMappings = "simulacaoMapping", parameters = {
                @StoredProcedureParameter(mode = ParameterMode.IN, type = Long.class, name = "P_ID_METRICA_FREQ"),
                @StoredProcedureParameter(mode = ParameterMode.IN, type = LocalDateTime.class, name = "P_DATA_INICIO"),
                @StoredProcedureParameter(mode = ParameterMode.REF_CURSOR, type = Class.class, name = "r_cursor") }) })
@SqlResultSetMappings({
        @SqlResultSetMapping(name = "simulacaoMapping", classes = @ConstructorResult(targetClass = SimulacaoVO.class, columns = {
                @ColumnResult(name = "data", type = LocalDateTime.class),
                @ColumnResult(name = "realizado", type = Double.class),
                @ColumnResult(name = "previsto", type = Double.class),
                @ColumnResult(name = "simulado", type = Double.class),
                @ColumnResult(name = "metrica_freq", type = Long.class)})) })
public class VwDashCamadaServidores implements Serializable {

   *// Variáveis com seus getters e setters*

}

Repositório

public interface VwDashCamadaServidoresRepository extends
        ViewRepository<VwDashCamadaServidores, VwDashCamadaServidoresPK> {

    @Procedure(name = "spSimularProjecao")
    Collection<SimulacaoVO> getSimulacaoProjecao(@Param("P_ID_METRICA_FREQ") Long idMetricaFreq,
            @Param("P_DATA_INICIO") LocalDateTime dtInicio);

}

Serviço

@Service
public class VwDashCamadaServidoresService {

    @Autowired
    private VwDashCamadaServidoresRepository repo;

    @Transactional
    public Collection<SimulacaoVO> getSimulacao(Long idMetricaFreq, LocalDateTime dtInicio) {
        return repo.getSimulacaoProjecao(idMetricaFreq, dtInicio);
    }

}

Controller

@RestController
@RequestMapping("rest/controller")
public class RestController {

    @PostMapping("/gerarSimulacaoPV")
    public ResponseEntity<Collection<SimulacaoVO>> gerarSimulacaoPV(Long idMetricaFreq, Date dtInicioProjecao) throws Exception {

        Collection<SimulacaoVO> lstSimulacaoVO = null;
        try {

            *// Aqui, em um dos parâmetros, uso uma Classe Util de converão de Data para LocalDateTime.*
            lstSimulacaoVO = vwDashCamadaServidoresService.getSimulacao(idMetricaFreq,
                    DateUtils.convertDateToLocalDateTime(dtInicioProjecao));

        } catch (Exception e) {

            logger.error(StringUtils.convertStackTraceToString(e));
            String msgError = "Ocorreu um erro inesperado ao consultar a Base de Dados!";
            throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, msgError);
        }

        return ResponseEntity.ok(lstSimulacaoVO);
    }

}

ERROR

[2022-03-04 12:05:06,775] [ERROR] [c.d.c.r.ProjecaoVegetativaRestController] : org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [oracle.jdbc.driver.ForwardOnlyResultSet] to type [com.cmis.dashboard.vo.SimulacaoVO]
    at org.springframework.core.convert.support.GenericConversionService.handleConverterNotFound(GenericConversionService.java:321)
    at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:194)
    at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:174)
    at org.springframework.data.repository.query.ResultProcessor$ProjectingConverter.convert(ResultProcessor.java:297)
    at org.springframework.data.repository.query.ResultProcessor$ChainingConverter.lambda$and$0(ResultProcessor.java:217)
    at org.springframework.data.repository.query.ResultProcessor$ChainingConverter.convert(ResultProcessor.java:228)
    at org.springframework.data.repository.query.ResultProcessor.processResult(ResultProcessor.java:156)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:157)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:142)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:618)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:605)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:367)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:118)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:149)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:95)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
    at com.sun.proxy.$Proxy278.getSimulacaoProjecao(Unknown Source)
    at com.cmis.dashboard.services.views.infra.analiseCamada.VwDashCamadaServidoresService.getSimulacao(VwDashCamadaServidoresService.java:36)

Já pesquisei bastante a respeito, mas a solução que eu encontrei ou utilizava o EntityManager ou anotação @Query com query nativa, que repito, não é o que eu gostaria.

Poderiam me ajudar?

Att, Kilmer.

1 Resposta 1

-2

Utilizando o SqlResultMappings você vai conseguir resolver o seu problema! https://vladmihalcea.com/jpa-sqlresultsetmapping/

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .