如何使用 jooq 连接 3 个表并迭代结果?
How to join 3 tables and iterate results using jooq?
我有课程、学生、时间表 tables.
table course(id, name, ....),
table student(id, name, ...),
table schedule(id, c_id, s_id).
现在我想离开加入时间表 table 与课程和学生 table。
问题 (1):
在 jooq 中加入这 3 个 table 的最佳方法是什么?我假设它是这样的:
TableLike<?> firstjoin = sql
.select()
.from(Tables.SCHEUDLE)
.leftOuterJoin(Tables.COURSE)
.on(Tables.SCHEDULE.CID.eq(Tables.COURSE.ID))
.asTable();
Result<?> result = sql
.select()
.from(firstjoin)
.leftOuterJoin(Tables.STUDENT)
.on(Tables.SCHEDULE.SID.eq(Tables.STUDENT.ID))
.fetch();
问题(2):
当我得到结果时,将结果拆分为学生对象和课程对象的最佳方法是什么?我的意思是因为类型是结果?有什么方法可以将结果映射到学生、课程实体,而不是像这样乏味地做一些事情:
for(Record r: result){
Student s = new Student(r.filed(), r.filed()...);
Course c = new Course(r.filed(), r.filed()....)
}
答案 1
What's the best way to do join these 3 tables in jooq? I assume it's like [...]
虽然您的查询正确,但我不会像您那样加入。您的方法创建了派生的 table,其中
- 为没有值的 SQL 语句增加复杂性,例如维护声明时
- 防止在某些处理派生 tables
的数据库中进行优化
相反,只需在一个语句中加入两个 table:
Result<?> result = sql
.select()
.from(SCHEUDLE)
.leftOuterJoin(COURSE)
.on(SCHEDULE.CID.eq(COURSE.ID))
.leftOuterJoin(STUDENT)
.on(SCHEDULE.SID.eq(STUDENT.ID))
.fetch();
答案 2
您可以使用多种 Record.into()
方法中的一种,例如 Record.into(Table)
for (Record r : result) {
StudentRecord s = r.into(STUDENT);
CourseRecord c = r.into(COURSE);
}
我有课程、学生、时间表 tables.
table course(id, name, ....),
table student(id, name, ...),
table schedule(id, c_id, s_id).
现在我想离开加入时间表 table 与课程和学生 table。
问题 (1):
在 jooq 中加入这 3 个 table 的最佳方法是什么?我假设它是这样的:
TableLike<?> firstjoin = sql
.select()
.from(Tables.SCHEUDLE)
.leftOuterJoin(Tables.COURSE)
.on(Tables.SCHEDULE.CID.eq(Tables.COURSE.ID))
.asTable();
Result<?> result = sql
.select()
.from(firstjoin)
.leftOuterJoin(Tables.STUDENT)
.on(Tables.SCHEDULE.SID.eq(Tables.STUDENT.ID))
.fetch();
问题(2):
当我得到结果时,将结果拆分为学生对象和课程对象的最佳方法是什么?我的意思是因为类型是结果?有什么方法可以将结果映射到学生、课程实体,而不是像这样乏味地做一些事情:
for(Record r: result){
Student s = new Student(r.filed(), r.filed()...);
Course c = new Course(r.filed(), r.filed()....)
}
答案 1
What's the best way to do join these 3 tables in jooq? I assume it's like [...]
虽然您的查询正确,但我不会像您那样加入。您的方法创建了派生的 table,其中
- 为没有值的 SQL 语句增加复杂性,例如维护声明时
- 防止在某些处理派生 tables 的数据库中进行优化
相反,只需在一个语句中加入两个 table:
Result<?> result = sql
.select()
.from(SCHEUDLE)
.leftOuterJoin(COURSE)
.on(SCHEDULE.CID.eq(COURSE.ID))
.leftOuterJoin(STUDENT)
.on(SCHEDULE.SID.eq(STUDENT.ID))
.fetch();
答案 2
您可以使用多种 Record.into()
方法中的一种,例如 Record.into(Table)
for (Record r : result) {
StudentRecord s = r.into(STUDENT);
CourseRecord c = r.into(COURSE);
}