如何在jpa本机查询中转换joda DateTime

dan*_*ter 7 hibernate jpa jodatime spring-data-jpa

我有一个实体,其中DateTime属性与hibernate持久存在

@Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
@Column(name = "EFF_DT")
protected DateTime effDt;
Run Code Online (Sandbox Code Playgroud)

这一切都适用于常规spring-data-jpa生成的查询.

我正在尝试添加自定义本机查询

 @Query(value = "SELECT COUNT(*) FROM wsa_circuit_state_history ch WHERE ch.eff_dt between ?1 and ?2", nativeQuery = true)
    Integer countEffDateBetween(DateTime start, DateTime end);
Run Code Online (Sandbox Code Playgroud)

我得到的错误是当试图调用它时

 java.sql.SQLException: ORA-00932: inconsistent datatypes: expected DATE got BINARY
Run Code Online (Sandbox Code Playgroud)

这是我在将自定义类型映射添加到我的实体之前使用常规spring-data finders时遇到的相同错误

 @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
Run Code Online (Sandbox Code Playgroud)

我如何使spring-data-jpa/hibernate使用自定义类型映射参数到本机查询?

Chr*_*ory 0

只需将您的属性设置为 java.util.Date 像这样

@Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
@Column(name = "EFF_DT")
@Temporal( TemporalType.TIMESTAMP )
protected Date effDt;
Run Code Online (Sandbox Code Playgroud)

然后在你的 getter/setter 中进行转换

public DateTime getEffDt() {
    return null == effDt ? null : new DateTime( effDt );
}

public void setEffDt( final DateTime effDt ) {
    this.effDt = null == effDt ? null : effDt.toDate();
}
Run Code Online (Sandbox Code Playgroud)

本国的:

@Query(value = "SELECT COUNT(*) FROM wsa_circuit_state_history ch WHERE ch.eff_dt between ?1 and ?2", nativeQuery = true)
Integer countEffDateBetween(Date start, Date end);
Run Code Online (Sandbox Code Playgroud)

  • 我们使用的是 DateTime,而不是 java.util.Date。当然,如果我们停止使用 DateTime 并使用 Date,我们就不会遇到这个问题。然而,我们希望使用更优越的 joda DateTime API。我的问题是“如何使本机查询与 DateTime 一起使用”,不使用 DateTime 不是这个问题的解决方案。 (2认同)