在spring-data-jpa中使用joda DateTime参数进行本机查询会因为绑定错误而失败

时间:2015-02-03 16:05:18

标签: java jpa spring-data jodatime spring-data-jpa

以下两个查询应该完全相同,除了一个标记为本机而另一个不标记为本机。第一个工作正常,但第二个工作失败了incompatible data type in conversion

  @Transactional(readOnly = true)
  @Query(value = "select startDate from TaskMetrics where startDate between :startDate and :endDate")
  List<DateTime> findStartDateByStartDateBetween(@Param("startDate") DateTime startDate,
  @Param("endDate") DateTime endDate);

这会生成查询:

select taskmetric0_.startDate as col_0_0_ from TaskMetrics taskmetric0_ where taskmetric0_.startDate between ? and ?

使用绑定

binding parameter [1] as [TIMESTAMP] - [2015-02-02 10:57:14.279]
binding parameter [2] as [TIMESTAMP] - [2015-02-04 10:57:14.281]

-

  @Transactional(readOnly = true)
  @Query(nativeQuery = true, value = "select startDate from TaskMetrics where startDate between :startDate and :endDate")
  List<DateTime> findStartDateBetween(@Param("startDate") DateTime startDate,
  @Param("endDate") DateTime endDate);

这会生成查询:

select startDate from TaskMetrics where startDate between ? and ?

使用一个绑定,这似乎有点奇怪(特别是为什么#2?):

binding parameter [2] as [VARBINARY] - [2015-02-04T10:57:14.315-05:00]

我正在使用Hibernate 4.3.8.Final作为我的JPA 2.1提供程序,使用Jadira Usertype 3.1.0.CR10作为JodaTime支持。

我做错了什么,或者这是某个地方的错误?

Bug在这里打开 - https://jira.spring.io/browse/DATAJPA-671

2 个答案:

答案 0 :(得分:2)

错误的解决方法:

  public class MyDaoClass {

    // Converter provided by joda time user type library 
    private TimestampColumnDateTimeMapper columnDateTimeMapper = new TimestampColumnDateTimeMapper();

    @Override
    public void doAction(MyObject myObject) {
        Query q = getEntityManager().createNamedQuery("MyNativeNamedQuery");
        q.setParameter("date", columnDateTimeMapper.toNonNullValue(myObject.getDate()), TemporalType.TIMESTAMP);
        q.executeUpdate(); // or select
    }

答案 1 :(得分:1)

第二个是nativeQuery因为我知道joda DateTime无效。请改用Java.sql.Date