How to convert javassist instance to instance of a specific domain

I would like to traverse two lists of instances of a specific domain class using grails 1.3.7.

The problem is that instances of the same list are created by javasisst, so the intersection result is always empty.

Here are my domains:

class User { ... static hasMany = [foos : Foo] ... } class Foo { ... static hasMany = [bars : Bar] ... } class Bar { ... static hasMany = [localizedTitles : LocalizedTitle] ... } 

I get a list of all Bar user instances as follows:

 def allBarsOfUser = userInstance.foos.bars.flatten() 

And try intersecting with another list of Bar instances:

 def intersectedBars = bars.intersect(allBarsOfUser) 

The problem is that the element type is allBarsOfUser ist Bar_$$_javassist_139 , and the element type of bars is Bar , so intersectedBars always [] .

I solved my problem by doing the following - but I don't like the solution:

 def allBarsOfUser = userInstance.foos.bars.flatten().collect{Bar.get(it.id)} 

What would be the best solution?

How do I make Bar_$$_javassist_139 to Bar so that intersect() works fine?

+2
source share
1 answer

It depends on what you are actually trying to do. The intersect method ultimately relies on equals , so if you implement equals and hashCode in Bar , then it will do what you want. But you should not usually implement equals from the point of view of the identifier of the object, since identifiers are assigned only when the object is saved, so you cannot compare a newly created object with a previously saved one. Hibernate recommends that you implement it based on a business key (something that is not a generated identifier, but that is stable and unlikely to change throughout the life of the object)

 class UserAccount { String username String realname public boolean equals(that) { return ((that instanceof UserAccount) && (this.username == that.username)) } public int hashCode() { username.hashCode() } } 

So, if you need matching identifiers, then it is clearer to do this explicitly.

 def userBarIds = allBarsOfUser*.id def intersectedBars = bars.findAll { it.id in userBarIds } 
+1
source

All Articles