2

Perhaps I'm misusing jOOQ, as I'm struggling to find a solution elsewhere for this use case.

I want to apply my own method to some rows in a jOOQ query, along the lines of:

create
    .update(USER)
    .set(USER.EMAIL, hash(EMAIL))
    .where(USER.ID.in(userIdsToUpdate))
    .execute();

Where hash(EMAIL) would return a hashed version of the email.

Obviously this syntax is invalid, but hopefully it conveys my intent.

Is there support for anything like this with jOOQ?

1 Answer 1

5

In case hash() is a vendor specific SQL function

hash() is probably a vendor specific hash function that you would like to use, but jOOQ doesn't offer it through the DSL API. The solution in this case is always to resort to plain SQL templating

public static Field<String> hash(Field<String> field) {
    return DSL.field("hash({0})", SQLDataType.VARCHAR, field);
}

Alternatively, you could roll your own using your database's stored procedure syntax and let the code generator pick it up for you

In case hash() is a Java method

You cannot let the database call your Java method from within a SQL query. If you want to hash all the emails from your table, you'd have to fetch all the records, modify the emails, and store them again. I recommend doing it in the database instead as that would be much faster, but if that's not an option, here's how you'd do it with jOOQ:

Result<UserRecord> users = create
    .select(USER.ID, USER.EMAIL)
    .from(USER)
    .where(USER.ID.in(userIdsToUpdate))
    .fetchInto(USER);

for (UserRecord user : users)
    user.setEmail(hash(user.getEmail()));

create.batchUpdate(users);
2
  • My hash function is a Java method. Will this solution still work in that case? Dec 10, 2018 at 10:41
  • 1
    No, you cannot let the database call your Java hash function. In that case, you would have to load all values into the client, call the hash function there, and store them again. Or better, re-implement the hash function as a stored function in your database.
    – Lukas Eder
    Dec 10, 2018 at 11:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.