使用日期条件时,JPA会缩短纳秒数。 SQL datetime2

时间:2015-06-04 12:24:43

标签: java sql-server hibernate jpa datetime2

我试图创建一个涉及SQL Server datetime2字段的where子句(精确到100纳秒);使用JPA&冬眠。

我的代码看起来像这样:

CriteriaBuilder cb = em.getCriteriaBuilder();
List<Predicate> predicates = new ArrayList<>();
CriteriaQuery(X) q = cb.createQuery(X.class);
Root<X> root = q.from(X.class);

java.sql.Timestamp mySqlTimeStamp = Timestamp.valueOf("2015-06-04 11:31:53.2119339");

predicates.add(cb.greaterThan(root.get("DateModified"), mySqlTimeStamp))

q.where(predicates.toArray(new Predicate[predicates.size()]));

em.createQuery(q).getResultList();

SQL Server Profiler显示时间戳参数值被截断为2015-06-04 11:31:53.210 - 奇怪的是,这甚至都不是舍入。有人说,我在结果集中有不准确之处。

如果我手动将参数更改为完整值2015-06-04 11:31:53.2119339,那么一切都很好。

问题是,如何让JPA 而不是截断日期?

或者,如何为我的时间戳字段注入自己的参数值序列化器?

帮助表示赞赏;谢谢

更新 我已经跟踪了这个jtds jdbc代码: net.sourceforge.jtds.jdbc.JtdsPerparedStatement

protected void setParameter(int parameterIndex, Object x, int targetSqlType, int scale, int length)
        throws SQLException {
        ParamInfo pi = getParameter(parameterIndex);

        if ("ERROR".equals(Support.getJdbcTypeName(targetSqlType))) {
            throw new SQLException(Messages.get("error.generic.badtype",
                                Integer.toString(targetSqlType)), "HY092");
        }

        // Update parameter descriptor
        if (targetSqlType == java.sql.Types.DECIMAL
            || targetSqlType == java.sql.Types.NUMERIC) {

            pi.precision = connection.getMaxPrecision();
            if (x instanceof BigDecimal) {
                x = Support.normalizeBigDecimal((BigDecimal) x, pi.precision);
                pi.scale = ((BigDecimal) x).scale();
            } else {
                pi.scale = (scale < 0) ? TdsData.DEFAULT_SCALE : scale;
            }
        } else {
            pi.scale = (scale < 0) ? 0 : scale;
        }

        if (x instanceof String) {
            pi.length = ((String) x).length();
        } else if (x instanceof byte[]) {
            pi.length = ((byte[]) x).length;
        } else {
            pi.length   = length;
        }

        if (x instanceof Date) {
            x = new DateTime((Date) x);
        } else if (x instanceof Time) {
            x = new DateTime((Time) x);
        } else if (x instanceof Timestamp) {
            x = new DateTime((Timestamp) x);
        }

        pi.value = x;
        pi.jdbcType = targetSqlType;
        pi.isSet = true;
        pi.isUnicode = connection.getUseUnicode();
    }
}

时间戳强制为net.sourceforge.jtds.jdbc.DateTime类型,仅支持毫秒。

1 个答案:

答案 0 :(得分:0)

这更像是一种解决方法;我所做的就是让问题消失:

如问题更新中所述,jtds驱动程序不支持datetime2参数。我只是转向Microsoft驱动程序 - 问题解决了。

一些进一步的解决方法:

  • 嵌入Convert()函数调用,包装参数文字;发送Timestamp字符串值。
  • 修复jtds代码 - 显然jdbc支持nanos
相关问题