首页 > 解决方案 > 从 Spring Data Jpa 运行查询时无法获得结果

问题描述

在 pgAdmin 中运行以下查询时,一切都很好,但是当我从 java 代码运行查询时出现错误。

我尝试转换变量但没有结果,我收到转换语法错误

查询界面:

public interface SeanceRepository extends JpaRepository<Seance, Integer>{

    @Query(value = "select * from seance, patient where extract(month from date) = ?1 "
            + "and extract(year from date) = ?2 and patient.id = seance.patient_id", 
              nativeQuery = true)
    public List<Object> getSeanceByMonthYear(String month, String year);
}

错误 :

org.postgresql.util.PSQLException: ERREUR: l'opérateur n'existe pas : double precision = character varying
  Indice : Aucun opérateur ne correspond au nom donné et aux types d'arguments.
Vous devez ajouter des conversions explicites de type.
  Position : 62
    at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2440) ~[postgresql-42.2.5.jar:42.2.5]
    at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2183) ~[postgresql-42.2.5.jar:42.2.5]
    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:308) ~[postgresql-42.2.5.jar:42.2.5]

病人.java

@Entity
@Table(name = "Patient")
@JsonIgnoreProperties({ "hibernateLazyInitializer", "handler" })
public class Patient {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    private String firstName;
    private String lastName;
    private String cin;
    private Date birthDate;
    private String phoneNumber;
    private Boolean active;

    //getters and setters
}

降神会.java

@Entity
@Table(name = "Seance")
@JsonIgnoreProperties({ "hibernateLazyInitializer", "handler" })
public class Seance {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    private Date date;

    @OneToOne
    private Patient patient;

    @OneToOne
    private TypeConsultation typeConsultation;

    private String motif;

    //getters and setters

标签: postgresqlspring-bootspring-data-jpaspring-data

解决方案


正如您在https://w3resource.com/PostgreSQL/extract-function.php中看到的

extract function() 用于从日期/时间值中检索子字段,例如年或小时。源必须是时间戳、时间或间隔类型的值表达式。该字段是一个标识符或字符串,用于选择要从源值中提取的字段。

句法:

提取(来自时间戳的字段)或提取(来自间隔的字段)

返回类型:双精度。

PostgreSQL 版本:9.3

extract 以双精度返回一个值,然后您尝试将其与 varchar 进行比较。它不能由 postgresSQL 自动完成,您必须明确地完成:

@Query(value = "select * from seance, patient where extract(month from date)::varchar(255) = ?1 "
        + "and extract(year from date)::varchar(255) = ?2 and patient.id = seance.patient_id", 
          nativeQuery = true)

推荐阅读