使用 GORM 无需再次访问数据库即可获取一对多加载对象的 ID [英] Getting the ID of a one-to-many loaded object without another trip to the DB with GORM
问题描述
我必须 GORM 域,A &B、与数据库表有关.A 与 B 是一对多的关系.因此,这些类看起来类似于:
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
}
当我检索 A 的实例时,会从数据库中检索 B 的相应实例的 ID.但是,当我尝试通过以下方式访问该 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
整个对象从数据库加载.在某些情况下,我只想要 B 的 ID(已经被检索到)并且不想从数据库加载整个实例.有没有办法从 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.
注意:我知道它在上面的 abid
行上做了一个额外的提取,因为我可以看到自从我打开 loggingSql
选项后生成的 SQL在我的数据源文件中.
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.
推荐答案
代替:
多头出价 = a.b.id
Long bid = a.b.id
使用:
多头出价 = a.bId
Long bid = a.bId
这篇关于使用 GORM 无需再次访问数据库即可获取一对多加载对象的 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!