findAll() Not Returning Correct Object Type

不羁岁月 提交于 2019-12-11 08:27:53

问题


ItemTag objects contain an Item object and a Tag object. (These are Java domain objects.)

This simple query works as expected. I get back a list ItemTags and can do all the wonderful things that ItemTags are supposed to do:

def theTags1 = ItemTag.findAll("from ItemTag  b")

For example:

println(theTags1[0].tag.tag)

gives me this as expected:

Pilgrim's Progress

However, as soon as I add another table to the criteria, instead of getting a list of ItemTags, I just get a list of generic objects.

e.g the following

def theTags2 = ItemTag.findAll("from ItemTag  b, Tag a where b.tag= a")

theTags2.each {
     theClass = it.getClass();
     nameOfClass = theClass.getName();
     println(nameOfClass)
}   

returns

[Ljava.lang.Object;
[Ljava.lang.Object;
[Ljava.lang.Object;

And I can't use the resulting objects at all. For example:

println(theTags2[0].tag.tag)

gives me this error:

Exception evaluating property 'tag' for java.util.ArrayList, Reason: groovy.lang.MissingPropertyException: No such property: tag for class: java.lang.String

and

def exTag2 = (ItemTag) theTags2[0]

gives me this error:

Cannot cast object '[Ljava.lang.Object;@2d81f' with class '[Ljava.lang.Object;' to class 'org.maflt.flashlit.pojo.ItemTag'

What do I need to do to get usable objects? Thanks!


回答1:


In Hibernate, the

"from ItemTag b, Tag a where b.tag= a"

query is a cross-join. The result of this query is a list of Object arrays where the first item is an ItemTag instance and the second is a Tag instance.

You have to use e.g.

(ItemTag) theTags2[0][0]

to access the first ItemTag instance.




回答2:


Assuming you are just trying to get the ItemTag object you can also change the HQL to something like:

def theTags2 = ItemTag.findAll("select b from ItemTag  b, Tag a where b.tag= a")

That tells it you only want one object. You should also be able to use a join condition I think something like:

def theTags2 = ItemTag.findAll("from ItemTag b where b.tag is not null")


来源:https://stackoverflow.com/questions/1093918/findall-not-returning-correct-object-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!