Home > Back-end >  Select all fields from the table with multiset
Select all fields from the table with multiset

Time:11-22

What is the best way to pass all fields to fetch table with multiset? If I have many fields in the table, then this method will be too large

return dsl.select(
                USER.asterisk(),
                multiset(
                    select(USER_ROLE.AUTHORITY_ID.as(ROLE.ID))
                        .from(USER_ROLE)
                        .where(USER_ROLE.USER_ID.eq(USER.ID)))
                    .as("roles")
                    .convertFrom(f -> f.intoSet(roleMapper)))
            .from(USER)
            .where(field.eq(value));

And will it be ok if my multiset returns roles and then I need to set it to the user in my record mapper?

@Override
@SuppressWarnings("unchecked")
public User map(Record record) {
    final User user = new User();
    user.setId(record.get(USER.ID));
    user.setEmail(record.get(USER.EMAIL));
    user.setPassword(record.get(USER.PASSWORD));
    user.setFirstName(record.get(USER.FIRST_NAME));
    user.setLastName(record.get(USER.LAST_NAME));
    user.setActivated(record.get(USER.ACTIVATED));
    user.setActivationKey(record.get(USER.ACTIVATION_KEY));
    user.setImageUrl(record.get(USER.IMAGE_URL));

    final Set<Role> roles = Optional.ofNullable(record.get("roles"))
            .map(r -> (Set<Role>) r)
            .orElse(Collections.emptySet());

    user.setRoles(roles);
    user.setResetKey(record.get(USER.RESET_KEY));
    user.setResetDate(record.get(USER.RESET_DATE));
    user.setLastModifiedBy(record.get(USER.LAST_MODIFIED_BY));
    user.setLastModifiedDate(record.get(USER.LAST_MODIFIED_DATE));
    user.setLangKey(record.get(USER.LANG_KEY));

    return user;
}

CodePudding user response:

You can extract all USER columns at once using record.into(USER):

UserRecord userRecord = record.into(USER);
// And then, for example:
User user = userRecord.into(User.class);

You can even let jOOQ do all of that for you by projecting a nested TableRecord like this (since jOOQ 3.17, Table<R> extends SelectField<R>):

return dsl.select(
                USER,
                multiset(...)
            .from(USER)
            ...

This produces a Record2<UserRecord, Result<...>> type, so you already have all the USER columns in a handy nested record.

  • Related