Hibernate:强制get()尊重其参数

时间:2017-12-06 14:59:17

标签: grails gorm

设置:使用Hibernate 4.3.10的Grails 2.5.6

我有一个带有字符串id的表。事实是,它的值是数字字符串,当我传入get()之类的值时,这似乎会导致"000000"陷入困境。

域类:

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

所以看起来在某些时候&00; 000000'和' 201715'以及其他任何被不方便地转换成Long对象的东西。使用as String也无济于事。任何人都可以帮我告诉Hibernate这个字符串应该被视为一个字符串吗?

1 个答案:

答案 0 :(得分:1)

这似乎是一个Grails错误,我猜这是因为你没有在你的域类中声明idString类型,因为它被映射到一个不同的字段(这是有道理的)。

您可以尝试添加

String id

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

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