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

孤人 提交于 2019-12-19 06:17:11

问题


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 know 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.


回答1:


Instead of:

Long bid = a.b.id

use:

Long bid = a.bId



来源:https://stackoverflow.com/questions/7232794/getting-the-id-of-a-one-to-many-loaded-object-without-another-trip-to-the-db-wit

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