Mutating data with jOOQ

Matthew Fitch :

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?

Lukas Eder :

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);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=130421&siteId=1