java jOOQ 我可以将两个表的连接提取到各自的 POJO 中吗

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38222957/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 03:13:32  来源:igfitidea点击:

jOOQ can I fetch a join of two tables into the respective POJOs

javajooq

提问by mat_boy

In jOOQ if I want to fetch a row of a table into a jOOQ autogenerated POJOs I do, for instance:

在 jOOQ 中,如果我想将表中的一行提取到 jOOQ 自动生成的 POJO 中,例如:

dsl.selectFrom(USER)
                .where(USER.U_EMAIL.equal(email))
                .fetchOptionalInto(User.class);

Now, suppose that I want to do a join between two tables, e.g. USERand ROLE, how can I fetch the result into the POJOs for these two tables?

现在,假设我想在两个表之间进行连接,例如USERand ROLE,我如何将结果提取到这两个表的 POJO 中?

回答by Lukas Eder

This is one solution using ResultQuery.fetchGroups(RecordMapper, RecordMapper)

这是使用的一种解决方案 ResultQuery.fetchGroups(RecordMapper, RecordMapper)

Map<UserPojo, List<RolePojo>> result =
dsl.select(USER.fields())
   .select(ROLE.fields())
   .from(USER)
   .join(USER_TO_ROLE).on(USER.USER_ID.eq(USER_TO_ROLE.USER_ID))
   .join(ROLE).on(ROLE.ROLE_ID.eq(USER_TO_ROLE.ROLE_ID))
   .where(USER.U_EMAIL.equal(email))
   .fetchGroups(

       // Map records first into the USER table and then into the key POJO type
       r -> r.into(USER).into(UserPojo.class),

       // Map records first into the ROLE table and then into the value POJO type
       r -> r.into(ROLE).into(RolePojo.class)
   );

Note, if you want to use LEFT JOINinstead (in case a user does not necessarily have any roles, and you want to get an empty list per user), you'll have to translate NULLroles to empty lists yourself.

请注意,如果您想LEFT JOIN改用(以防用户不一定具有任何角色,并且您想为每个用户获取一个空列表),则必须自己将NULL角色转换为空列表。

Make sure you have activated generating equals()and hashCode()on your POJOs in order to be able to put them in a HashMapas keys:

确保您已在 POJO 上激活生成equals()hashCode(),以便能够将它们HashMap作为键放入 a中:

<pojosEqualsAndHashCode>true</pojosEqualsAndHashCode>