Search code examples
grailsgrails-orm

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


Setup: Grails 2.5.6 with Hibernate 4.3.10

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

The exception thrown is:

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

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?


Solution

  • 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.

    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.