Reputation: 10665
I dont know how to describe the problem, so weird. I have function like this:
long getPersonId(...){
//...
}
The above function returns Id of a person based on some arguments.
So I logged the return value of the function and it is 1
.
Then I have code like this:
person = myMap.get(getPersonId(..))
which returns null object but this returns a valid Person object, why?:
person = myMap.get(1)
But as I described before getPersonId(..)
returns 1
, which basically means
myMap.get(getPersonId(..)) == myMap.get(1)
myMap
is typed as Map<Long, Person> myMap
What is happening here?
Upvotes: 0
Views: 60
Reputation: 122364
In Groovy, as in Java, 1
is an int literal, not a long, so
myMap.get(1)
is attempting to look up the key Integer.valueOf(1)
, whereas
myMap.get(getPersonId(..))
is looking up the key Long.valueOf(getPersonId(...))
. You need to make sure that when you populate the map you are definitely using Long
keys rather than Integer
ones, e.g.
myMap.put(1L, somePerson)
In your original version of this question you were calling the GORM get
method on a domain class rather than the java.util.Map.get
method, and that should work as required as the GORM method call converts the ID to the appropriate type for you before passing it on to Hibernate.
Upvotes: 3
Reputation: 10665
I am so sorry the problem was when I initialize the map myMap
Map<Long, Person> myMap = [1, new Person()]
when you say something like this the key is an integer
but not a long
still groovy not complaining.
So the problem is my method was returning a long value (1L
) but my actual key on the map is integer value(1
).
So changing my map init to Map<Long, Person> myMap = [1L, new Person()]
solved the problem.
Probably this due to dynamic nature groovy but irritating unless you know how dynamic langs behave lol.
Upvotes: 1