JOOQ fetch over foreign keys table

泄露秘密 提交于 2021-02-05 08:11:41

问题


I have three tables:

Users
Keys
UserKeys

The UserKeys table has both primary keys from Users and Keys tables to establish the relation between users and keys.

How to fetch a User with all it's related keys?

What if additional tables exist (for instance UserRoles), etc. In general, how to fetch a user and all associated rows, related via foreign keys tables?


回答1:


Using standard SQL JOIN

I'm assuming you're using jOOQ's code generator. You write a join just like you would write a join in SQL:

ctx.select() // Optionally, list columns here, explicitly
   .from(USERS)
   .join(USER_KEYS).on(USERS.ID.eq(USER_KEYS.USER_ID))
   .join(KEYS).on(USER_KEYS.KEY_ID.eq(KEYS.ID))
   .where(USERS.NAME.eq("something"))
   .fetch();

Nesting collections

What if additional tables exist (for instance UserRoles), etc. In general, how to fetch a user and all associated rows, related via foreign keys tables?

I'm not sure if this is still the same question. The above may have been about how to do joins in general, this one seems to be more specific about how to fetch nested collections?

Because a JOIN will always produce cartesian products, which are undesirable, once you're joining several to-many paths. Starting from the upcoming jOOQ 3.14, you can use SQL/XML or SQL/JSON as a workaround for this, if your database supports that. For example:

List<Student> students =
ctx.select(jsonObject(
     jsonEntry("id", USERS.ID),
     jsonEntry("name", USERS.NAME),
     jsonEntry("keys", field(
       select(jsonArrayAgg(jsonObject(KEYS.NAME, KEYS.ID)))
       .from(KEYS)
       .join(USER_KEYS).on(KEYS.ID.eq(USER_KEYS.KEY_ID))
       .where(USER_KEYS.USER_ID.eq(USER.ID))
     )),
     jsonEntry("roles", field(
       select(jsonArrayAgg(jsonObject(ROLES.NAME, ROLES.ID)))
       .from(ROLES)
       .join(USER_ROLES).on(ROLES.ID.eq(USER_ROLES.ROLE_ID))
       .where(USER_ROLES.USER_ID.eq(USER.ID))
     ))
   ))
   .from(USERS)
   .where(USERS.NAME.eq("something"))
   .fetchInto(User.class);

Assuming the User class looks like this, and that you have Gson or Jackson on your classpath to map from JSON to your Java data structures:

class Key {
  long id;
  String name;
}

class Role {
  long id;
  String name;
}

class User {
  long id;
  String name;

  List<Key> keys;
  List<Role> roles;
}

Of course, you don't have to map to Java data structures and produce a JSON result directly, without further mapping. See also this blog post for more details.

Using multiple queries

If you cannot use the above approach, because you can't work with jOOQ 3.14 (yet), or because your RDBMS doesn't support SQL/XML or SQL/JSON, you can run several queries and assemble the results manually on your end.



来源:https://stackoverflow.com/questions/64378772/jooq-fetch-over-foreign-keys-table

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