JDBC查询传递Joda-Time DateTime.minusDays()生成对象时报错
解决JDBC传递Joda-Time DateTime参数时的PSQLException问题
问题描述
执行JDBC查询时,直接传递DateTime.now()作为参数正常,但传递now.minusDays(60)生成的DateTime实例时抛出异常:
nested exception is org.postgresql.util.PSQLException: Can't infer the SQL type to use for an instance of org.joda.time.DateTime. Use setObject() with an explicit Types value to specify the type to use.
实体类字段定义:
@CreatedDate @NotNull @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime") @Column(name = "created_date", nullable = false, updatable = false) @ColumnDefault("now()") protected DateTime createdDate = DateTime.now();
原因分析
PostgreSQL JDBC驱动对Joda-Time DateTime的自动类型推断存在局限性:DateTime.now()生成的实例因默认时区、精度与数据库类型更匹配,能被驱动自动识别;但经过minusDays()调整后的实例,驱动无法自动映射到对应的SQL类型(如TIMESTAMP)。
解决方案
1. 转换为JDBC原生支持的类型
将DateTime转换为java.sql.Timestamp或java.sql.Date,直接传递原生类型参数:
DateTime now = DateTime.now(); DateTime lookbackDays = now.minusDays(60); // 转换为Timestamp(适配带时间的字段) Timestamp lookbackTimestamp = new Timestamp(lookbackDays.getMillis()); // 若仅需日期部分,可转换为Date // Date lookbackDate = new Date(lookbackDays.getMillis()); // 查询时传入转换后的参数
2. 原生JDBC显式指定SQL类型
使用setObject()方法时,明确指定SQL类型为Types.TIMESTAMP:
PreparedStatement stmt = conn.prepareStatement("SELECT * FROM table WHERE created_date >= ?"); stmt.setObject(1, lookbackDays, Types.TIMESTAMP); ResultSet rs = stmt.executeQuery();
3. JPA/Hibernate中显式绑定参数类型
如果用JPA或Hibernate,设置参数时指定TemporalType:
Query query = entityManager.createQuery("SELECT e FROM Entity e WHERE e.createdDate >= :lookback"); query.setParameter("lookback", lookbackDays, TemporalType.TIMESTAMP); List<Entity> result = query.getResultList();
4. 检查Jadira依赖配置
确保项目中Jadira Usertype依赖完整,版本与Hibernate/JPA兼容,让ORM框架自动处理类型转换:
<!-- Maven依赖示例 --> <dependency> <groupId>org.jadira.usertype</groupId> <artifactId>usertype.core</artifactId> <version>6.0.1.GA</version> </dependency>
内容的提问来源于stack exchange,提问作者user404
相关产品推荐
相关产品推荐

