【问题标题】:LocalTime with spring-data-jpa and mssql使用 spring-data-jpa 和 mssql 的 LocalTime
【发布时间】:2017-09-29 15:56:26
【问题描述】:

在 MSSQL DB 上使用 LocalTime 的查询存在问题

我们的实体有字段

@Column(name = "receipt_time", nullable = false)
private LocalTime receiptTime;

一切正常,除了查询时,即使用 spring-data-jpa 查询

boolean existsByReceiptTime(LocalTime time);

返回The data types time and datetime are incompatible in the equal to operator.

我尝试使用 sendTimeAsDateTime 解决,但没有成功。不接受 url 字符串。然后我尝试了一些 AttributeConverters 无济于事。还有其他可能的建议吗?注意:我真的很喜欢使用 LocalTime 类型。

更新: 生成的查询是

Hibernate: select TOP(?) receipt0_.id as col_0_0_ from receipt receipt0_ where receipt0_.receipt_time=?' is the query.

【问题讨论】:

  • 我们也在使用正确的方言 SQLServer2012Dialect
  • 我实际上写了自己的转换器,它没有帮助。将尝试上面链接中提到的那个
  • 根据 JPQL 定义“existsByReceiptTime”生成的内容。此外,处理查询的是您的 JPA 提供程序,而不是 Spring,因此使用了来自任何 JPA 提供程序的堆栈跟踪
  • 我们已经 4 年多了,我仍然有同样的问题与 spring boot 2.6.3,LocalTime 列导致查询错误。除了编写转换器之外,还有什么新的解决方案吗?

标签: sql-server spring hibernate jpa spring-data-jpa


【解决方案1】:

解决方法是编写自定义属性转换器。这可能是 Microsoft SQL 服务器特定的解决方案。

@Converter(autoApply = true)
public class LocalTimeConverter implements AttributeConverter<LocalTime, String> {

    @Override
    public String convertToDatabaseColumn(LocalTime time) {
       return time.toString();
    }

    @Override
    public LocalTime convertToEntityAttribute(String time) {
       return LocalTime.parse(time);
    }
}

【讨论】:

    猜你喜欢
    • 2015-05-31
    • 2017-04-01
    • 1970-01-01
    • 2017-11-29
    • 2016-06-22
    • 1970-01-01
    • 2015-11-03
    • 2012-11-09
    • 2019-07-20
    相关资源
    最近更新 更多