开发者

Gorm returned value type

I have an object Foo with a hasMany association to a Bar object

class Foo {
 String value
 static hasMany = [
  bars: Bar
 ]
}

class Bar {
 String value
}

when i try the follwing

def foo = Foo.find("from Foo f where f.value=:value",[value:value])

the type of the returned value foo is Foo, while when i do this

def foo = Foo.find("from Foo f left join f.b开发者_StackOverflow社区ars b where b.value=:value",[value:value])

the type is an Object

Can anyone explain to me why ?

Thx, ken.


Because the second query selects properties of not just Foo but also Bar. If you println foo, the output for the second foo is something like this:

[Foo : 3, Bar : 2]

If you add loggingSql = true to your dataSource definition, Hibernate will output the actual SQL it's using to STDOUT - something like:

select
    foo0_.id as id0_0_,
    bar2_.id as id2_1_,
    foo0_.version as version0_0_,
    foo0_.value as value0_0_,
    bar2_.version as version2_1_,
    bar2_.value as value2_1_ 
from
    foo foo0_ 
left outer join
    foo_bar bars1_ 
        on foo0_.id=bars1_.foo_bars_id 
left outer join
    bar bar2_ 
        on bars1_.bar_id=bar2_.id 
where
    bar2_.value=?

OK. But how to avoid returning the Bar from the query? - I currently don't have a good solution.

I'd vote for using the select clause with HQL, but in practice any of those syntaxes will produce an error in GORM. It may be possible to solve this by using a Hibernate Criteria, but I currently don't know how.

So, for a start, you might simply want to state:

def fooBar = Foo.find("from Foo f left join f.bars b where b.value=:value",
   [value:value])
def foo = fooBar[0]
assert foo instanceof Foo

EDIT: Note that for one-to-one associations the "dotty" syntax can be used, i.e.,

from Foo foo where foo.baz.value=:value
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜