Is it good to use domain objects in Sets or as keys in Maps?
I did a lot of things in the past
Set<Book> someBooks = [] as Set someBooks.addAll (Book.findAllByAuthorLike('%hofstadter%')) someBooks.add (Book.findByTitleLike ('%eternal%'))
However, I noticed that problems often occur when findAllByAuthorLike can return a list of Hibernate Proxy objects com.me.Book_$$_javassist_128 , but findByTitleLike will return the correct com.me.Book object. This causes duplicates in the set because the real object and proxies are considered not equal.
I believe that I need to be very careful when using sets of domain objects like this, and I feel that this may be something that I should not do in the first place.
An alternative is, of course, using the / map id set, but that makes my code verbose and misunderstood
Set<Integer> someBooks = [] as Set // a set of id for books
@Burt: I thought Grails domain classes already did this, at least so that equals / compare runs in class / id and not in the instance of the object. Do you mean a special comparator for sleeping proxies?
return (this.class == obj.class && this.id == obj.id) || (obj.class == someHibernateProxy && this.id == obj.id)
Akusete
source share