Hibernate:强制 get() 遵守其参数的数据类型

Hibernate: force get() to respect the data type of its parameter

设置:Grails 2.5.6 和 Hibernate 4.3.10

我有一个带有字符串 ID 的 table。问题是,它的值是数字字符串,当我传入 "000000".

这样的值时,这似乎搞砸了 get()

域class:

class Term
{
  static mapping = {
    id name: 'code', generator: 'assigned'
    version false
    code column: 'CODE'
    description column: 'DESC'
  }

  String code
  String description
}

数据看起来像:

CODE   || DESC
-------++---------------------------
000000 || The Beginning of Time
201715 || Post Secondary Winter 2017
201815 || Post Secondary Winter 2018
999999 || The End of Time

然后在测试中我发现了以下内容:

assert Term.list()          // works fine
assert !Term.get('foo')     // works fine
//assert Term.get('000000') // throws exception

抛出的异常是:

Method threw 'org.springframework.orm.hibernate4.HibernateSystemException' exception.
Provided id of the wrong type for class Term. Expected: class java.lang.String, got class java.lang.Long
org.hibernate.TypeMismatchException: Provided id of the wrong type for class Term. Expected: class java.lang.String, got class java.lang.Long

所以看起来在某些时候“000000”和“201715”以及其他任何东西都被不方便地转换为 Long 对象。使用 as String 也无济于事。谁能帮我告诉 Hibernate 这个 String 应该被当作一个 String 来对待?

这似乎是一个 Grails 错误,我猜这是因为您没有在您的域 class 中将 id 声明为 String 类型,因为它被映射到一个不同的领域(这是有道理的)。

您可以尝试添加

String id

到您的域 class 尽管这可能不会导致列生成所需的行为。

我建议您可以使用 findByCode() 而不是 get(),因为您已将您的 ID 映射到 code 字段,结果应该是相同的。