【问题标题】:JPA Native Query with IN statement带有 IN 语句的 JPA 本机查询
【发布时间】:2020-02-19 06:49:58
【问题描述】:

我正在尝试在 springboot JPA 中使用 nativeQuery

Query(value = "select * from sms.outgoing_message where create_ts between timestamp(?1) and timestamp(?2) and (error_code IN (?3) or (error_code = '0' and error_msg not like '%Opt out%') or (error_code = '1' and (error_msg like '%21211%' or error_msg like '%21612%' or error_msg = 'Mobile number format is wrong')))", nativeQuery = true)
  List<OutgoingMessage> getBounceBackPhoneNumbers(LocalDateTime from, LocalDateTime to, List<String> listSoftBounceErrorCodes);

以上查询返回空结果。

当我尝试使用 30008,30005,30007,30003,30006 而不是 ?3 之类的错误代码时,它会给我更多结果

知道可能是什么问题吗?

【问题讨论】:

  • 可能有多个记录,您将给定代码绑定到您的查询。或者,可能存在语法问题。
  • 我怀疑你的时间戳部分没有正确传递,你能把调用代码放在这里

标签: sql spring-boot jpa


【解决方案1】:

如果您在 JPA 中使用 LocalDateLocalDateTime,则需要自己定义到 java.sql.Date 或 java.sql.Timestamp 的映射。

在您的情况下,LocalDateTime 和 java.sql.Timestamp 之间的转换是使用 Timestamp 的转换方法完成的。

import java.time.LocalDateTime;
import java.sql.Timestamp;

@Converter(autoApply = true)
public class LocalDateTimeAttributeConverter implements AttributeConverter<LocalDateTime, Timestamp> {

    @Override
    public Timestamp convertToDatabaseColumn(LocalDateTime locDateTime) {
        return locDateTime == null ? null : Timestamp.valueOf(locDateTime);
    }

    @Override
    public LocalDateTime convertToEntityAttribute(Timestamp sqlTimestamp) {
        return sqlTimestamp == null ? null : sqlTimestamp.toLocalDateTime();
    }
}

参考:persist-localdate-localdatetime-jpa

【讨论】:

  • 如果我硬编码 listSoftBounceErrorCodes / ?3 它工作正常,所以不要认为 lodaldatetime 有问题。我认为通过 list 的 'IN' 语句存在问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-15
  • 2019-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-08
相关资源
最近更新 更多