开发者

Getting the ID of a one-to-many loaded object without another trip to the DB with GORM

开发者 https://www.devze.com 2023-03-31 07:26 出处:网络
I have to GORM domains, A & B, that relate to database tables. A has a one-to-many relationship with B. Because of this, the classes look similar to:

I have to GORM domains, A & B, that relate to database tables. A has a one-to-many relationship with B. Because of this, the classes look similar to:

class A {
   B b
   Long id
}

class B {
   Long id
}

When I retrieve an instance of A the ID of the corresponding instance of B is retrieved from the database. However, when I attempt to access that ID via something like:

A a = A.get(11)
Long bid = a.b.id

the whole object is loaded from the database. In some cases I only want the ID of B (which has already been retrieved) and do not want to load the whole instance from the database. Is there a way to get the ID from B without going back and fetching the whole object.

NOTE: I kn开发者_StackOverflowow that it is doing an extra fetch on the line with a.b.id above because I can see the SQL being generated since I turned on the loggingSql option in my DataSource file.


Instead of:

Long bid = a.b.id

use:

Long bid = a.bId

0

精彩评论

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

关注公众号