Grails: Checking whether a detached object is in an attached Set
The session of my application contains a user objects which has a settings objects which contains an attribute "effectiveOrganisation". The settings objects is loaded eagerly and since the Hibernate Session is per request, the user object in the session is detached from the Hibernate Session.
I want to check wheter the "effectiveOrganisation" is in the Set of an attached object:
<g:if test="${session.user.settings.effectiveOrganisation in
documentInstance.downloadingOrganisations}">
But the result of this test is always false. Maybe this is because the organisation in the session and the organisation of the documentInstance are not identical objects. I implemented equals
and hashCode
in the Organisation
class but it didn't help.
I tried the following test in a controller:
def org = session.user.settings.effectiveOrganisation
doc.downloadingOrganisations.each{
if(it.equals(org))
println("equals works")
}
if(! doc.downloadingOrganisations.contains(org))
println("contains doesn't work")
The surprising result is:
equals works
contains doesn't work
equals
and hashCode
looks as follows:
boolean equals(o) {
if (this.is(o)) return true;
if (getClass() != o.class) return false;
Organisation that = (Organisation) o;
if (name != that.name) return false;
if (selfInspecting != that.selfInspecting) return false;
return true;
}
int hashCode() {
int result;
result = (name != null ? name.hashCode() : 0);
result = 31 * result + (selfIns开发者_Python百科pecting != null ? selfInspecting.hashCode() : 0);
return result;
}
How can I check wheter an object from the session is contained in the set of an attached object?
It looks like your hashcode computation is probably the issue. Hashcode is usually a lot cheaper to calculate than equals, so it's compared first. If there's a collision and two different objects generate the same hashcode, then equals() is checked. But if two objects have different hashcodes then according to the hashcode/equals contract they are assumed to be different objects.
The instances in the collection are proxies - is that affecting the hashcode calculation?
Check the class of the instances. The hash code is probably not the issue, but the objects are most likely hibernate proxies which is the issue.
Check if equals() is being called during contains()
Also, changing this g:if to
g:if test="${session.user.settings.id in
documentInstance.downloadingOrganisations*.id}"
May fix it.
精彩评论