Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

2.6K
Vistas
Spring data jpa consulta nativa con parámetro nulo (PostgreSQL)

La pregunta es ¿cómo hacer que mi consulta nativa acepte un parámetro nulo?

Aquí está mi consulta:

 @Query(value = "SELECT " + " summaries.event_type as \"eventType\", " + " summaries.institution_id as \"institutionId\", " + " identifiers.id as \"studentIdentifierId\", " + " identifiers.name as \"studentIdentifierName\" " + "FROM summaries " + "LEFT JOIN roles ON summaries.student_id=roles.id " + "LEFT JOIN identifiers ON roles.identifier_id=identifiers.id " + "WHERE " + " summaries.student_id IS NOT NULL AND " + " summaries.event_type IN (:eventTypes) AND " + " (:identifierId IS NULL OR roles.identifier_id=:identifierId) " + "GROUP BY " + " summaries.institution_id, " + " summaries.student_id, " + " identifiers.id, " + " identifiers.name, " + " summaries.event_type", nativeQuery = true) List<CustomProjection> findByCustomCondition( @Param("identifierId") Long identifierId, @Param("eventTypes") List<String> eventTypes);

Y ahora, cuando paso el identifierId como nulo, recibo el error:

 InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet. Caused by: org.postgresql.util.PSQLException: ERROR: operator does not exist: bigint = bytea HINT: No operator matches the given name and argument types. You might need to add explicit type casts.

Parece que la línea (:identifierId IS NULL OR roles.identifier_id=:identifierId) causa un problema aquí, pero realmente no puedo encontrar una buena solución, según tengo entendido, debería funcionar normalmente (cuando uso esta consulta directamente en pgAdmin funciona como debería, así que estoy bastante seguro de que es un problema relacionado con el mapeo).

Traté de emitir el identificador ( cast(:identifierId as bigint) ), pero no ayudó.

PD. es un proyecto un poco heredado, así que estas son las versiones que uso:

 compile group: 'org.springframework.data', name: 'spring-data-jpa', version: '1.11.6.RELEASE' compile group: 'org.postgresql', name: 'postgresql', version: '42.2.2' compile group: 'org.hibernate', name: 'hibernate-core', version: '5.2.17.Final'
over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

Este es un problema común con Hibernate + PostgreSQL, y la solución es implementar ese método usted mismo, en lugar de que Spring lo haga por usted. Dentro de la implementación tienes que hacer algo como esto

 List<CustomProjection> findByCustomCondition( @Param("identifierId") Long identifierId, @Param("eventTypes") List<String> eventTypes) { // entityManager is acquired with the @PersistenceContext annotation as an injectable Query q = entityManager.createNativeQuery(..., CustomProjection.class); // the important part: q.setParameter("identifierId", 0L); q.setParameter("identifierId", identifierId); ...

La primera llamada a setParameter garantiza que Hibenate utilice el definidor de tipos correcto, la segunda llamada anula el primer valor sin haber ejecutado la consulta y omite la detección de tipos.

over 4 years ago · Santiago Trujillo Denunciar

0

Modifique la consulta agregando espacio entre roles.identifier_id=:identifierId debe ser como roles.identifier_id= :identifierId

over 4 years ago · Santiago Trujillo Denunciar

0

Tendrá que usar lo siguiente en su lugar: (cast(:identifierId as bigint) IS NULL OR roles.identifier_id=:identifierId)

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda