Hibernate:强制get()尊重其参数的数据类型 [英] Hibernate: force get() to respect the data type of its parameter

查看:240
本文介绍了Hibernate:强制get()尊重其参数的数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

安装程序:使用Hibernate 4.3.10的Grails 2.5.6

Setup: Grails 2.5.6 with Hibernate 4.3.10

我有一个带有字符串id的表。事情是,它的值是数字字符串,并且当我传递一个值,例如000000时,这似乎弄乱了 get code>。

I have a table with a string id. Thing is, its values are numeric strings, and this seems to mess up get() when I pass in a value such as "000000".

域类:

Domain class:

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

  String code
  String description
}

数据如下所示:

Data looks like:

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

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

And then in testing I found the following:

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'以及其他任何正在被不方便地转换成长物体的东西。使用作为字符串也没有帮助。任何人都可以帮助我告诉Hibernate这个字符串应该被当作字符串吗?

So it looks like at some point the '000000' and the '201715' and whatever else are being inconveniently converted into Long objects. Using as String doesn't help either. Can anyone help me tell Hibernate that this String should be treated as a String?

推荐答案

这看起来像是一个Grails错误, m猜测是因为你没有在你的域类中声明 id 类型为 String ,因为它被映射到一个不同的领域(这是有道理的)。

This seems like a Grails bug and I'm guessing it is because you have not declared id to be of type String in your domain class because it is mapped to a different field (which makes sense).

您可以尝试添加

You could try adding

String id

添加到您的域类中,但这可能不会导致列生成期望的行为。

to your domain class although that may not caused desired behaviour with column generation.

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

I would suggest rather than using get() you could use findByCode() as you have mapped your id to the code field and the result should be the same.

这篇关于Hibernate:强制get()尊重其参数的数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆