HSQL + Hibernate 异常:错误的列类型:找到:双精度,预期:浮点

2023-12-03

我将内存中的 HSQL (HSQLDB) 与 Hibernate 一起用于我的所有单元测试,因为它非常快。我有一个表,其中的列定义如下:

float qw;

当休眠启动时,我收到以下错误:

org.hibernate.HibernateException: Wrong column type in MyTable for column qw. 
Found: double, expected: float

为什么会发现double当该列声明为float?


发生这种情况是由于一系列不幸事件.

  1. 问题始于 HSQLDB 不支持float数据类型。

    (Duh? Yes, I know, but Documentation here.)

  2. 由于 HSQLDB 确实如此,问题开始变得丑陋 不简单fail当你指定一个float专栏,但它 默默地将其重新解释为double。如果稍后查询类型 的那一栏,你会发现它不是float, it is double.

    A typical example of programmers applying their misguided notions of "defensive programming", creating far more trouble than they are saving. HSQLDB is essentially pretending to the unsuspecting programmer that everything went fine, but it is only trolling them: nothing went fine, and there will be trouble.

  3. 然后,稍后,hibernate 发现该列是double,同时它 期望它是float,而且它还不够聪明,无法知道这一点float 是可分配的 from double,所以失败了。

    Everyone knows that a double is better than a float, so hibernate should actually be happy that it found a double while all it needed was a float, right? --but no, hibernate will not have any of that: when it expects a float, nothing but a float will do.

  4. 然后,关于 hibernate 据说有一个有趣的事情 对 HSQLDB 的内置支持,事实证明它 包括一个class org.hibernate.dialect.HSQLDialect, but 这 方言不处理浮动。

    So, they don't believe that a data type incompatibility is a dialect issue? they never tested it with floats? I don't know what to suppose, but the truth of the matter is that the hibernate dialect for HSQLDB does not provide any correction for this problem.

所以,我们能做些什么?

该问题的一种可能的解决方案是为 HSQLDB 创建我们自己的休眠方言,在其中我们纠正了这种差异。

过去我在 MySQL 中也遇到过类似的问题boolean vs. bit,(参见这个问题:Hibernate 4 升级后“发现:位,预期:布尔值”)所以对于 HSQLDB 我解决了这个问题float vs. double通过声明我自己的 Hibernate HSQLDB 方言:

/**
 * 'Fixed' HSQL Dialect.
 *
 * PEARL: HSQL seems to have a problem with floats.  We remedy this here.
 * See https://stackoverflow.com/q/28480714/773113
 *
 * PEARL: this class must be public, not package-private, and it must have a 
 * public constructor, otherwise hibernate won't be able to instantiate it.
 */
public class FixedHsqlDialect extends HSQLDialect
{
    public FixedHsqlDialect()
    {
        registerColumnType( java.sql.Types.FLOAT, "double" );
    }
}

并按如下方式使用它:

ejb3cfg.setProperty( "hibernate.dialect", FixedHsqlDialect.class.getName() );
    //Instead of: org.hibernate.dialect.HSQLDialect.class.getName();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

HSQL + Hibernate 异常:错误的列类型:找到:双精度,预期:浮点 的相关文章

随机推荐