我有一个具有DateTime属性的实体,该实体可以保持休眠状态

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

对于常规的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);

我收到的错误是尝试调用此错误时
 java.sql.SQLException: ORA-00932: inconsistent datatypes: expected DATE got BINARY

这是我在将自定义类型映射添加到我的实体之前使用常规spring-data查找器时遇到的相同错误
 @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")

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

最佳答案

确实我也有相同的要求,我通过注册自定义类型以 hibernate 配置来解决它。

对于本机查询,TypeDefs不足以让Hibernate查找用户类型,它需要Type解析器来查找其类型。

@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);

在这种情况下,hibernate尝试从类型解析器中猜测类型(org.joda.time.DateTime)。
Type type = session.getFactory().getTypeResolver().heuristicType(typename);

由于没有DateTime的解析器,因此它将获得默认类型(可序列化的类型)。DateTime的值将强制转换为其类型,并被序列化并持久存储在DB中,该数据库由于二进制值大而失败。

要解决此问题,您需要将DateTime类型注册为Hibernate Configuration作为
configuration.registerTypeOverride(new org.jadira.usertype.dateandtime.joda.PersistentDateTime(), new String[]{"org.joda.time.DateTime"});

07-25 23:52
查看更多