我有一个与另一个表有一对一关系的表,但是有两个表,src 和 dst,如何加入它对吗?我做了类似的事情,但不确定这是最佳做法:
val route = tbl.`as`("route")
val srcPlace = Tables.PLACE.`as`("srcPlace")
val dstPlace = Tables.PLACE.`as`("dstPlace")
val records = dsl
.select(route.asterisk())
.select(srcPlace.asterisk())
.select(dstPlace.asterisk())
.from(route)
.join(srcPlace).on(route.SRC_ID.eq(srcPlace.ID))
.join(dstPlace).on(route.DST_ID.eq(dstPlace.ID))
.limit(pageable.pageSize)
.offset(pageable.offset)
.fetch {
val r = it.into(route).into(RouteEntity::class.java)
val sP = it.into(srcPlace).into(PlaceEntity::class.java)
val dP = it.into(dstPlace).into(PlateEntity::class.java)
r.srcPlace = sP
r.dstPlace = dP
r
}
如何做得更好?
最佳答案
最简单的方法(从 jOOQ 3.17 和 the ability of projecting table expressions as SelectField
开始)是只投影表本身,例如:
dsl.select(route, srcPlace, dstPlace)
. // query
.fetch {
val (r, sP, dP) = it
// ...
}
在您的特定情况下,您甚至可以使用 implicit joins 进一步简化事情
// Assuming you named your foreign keys "src" and "dst"
dsl.select(route, route.src, route.dst)
.from(route)
.limit(pageable.pageSize)
.offset(pageable.offset)
.fetch {
val (r, sP, dP) = it
// ...
}
甚至,没有 it
解构:
// Assuming you named your foreign keys "src" and "dst"
dsl.select(route, route.src, route.dst)
.from(route)
.limit(pageable.pageSize)
.offset(pageable.offset)
.fetch { (r, sP, dP) ->
// ...
}
关于spring-boot - 如何在 jOOQ 中两次加入同一张表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72812509/