Home > Blockchain >  Using JOOQ, why would you use DSL.param() in insertInto().values()?
Using JOOQ, why would you use DSL.param() in insertInto().values()?

Time:12-04

I'm new to JOOQ and trying to get up to speed on an existing codebase (unfortunately the developer responsible for this particular code is no longer with us).

The insert code looks something like this (simplified) :

public class User {

    public static Table<?> table = DSL.table("user");

    public static Field<String> firstName = DSL.field(DSL.name(table.getName(), "first_name"), String.class);
    public static Field<String> lastName = DSL.field(DSL.name(table.getName(), "last_name"), String.class);
}

private class UserDto {

    private String firstName;
    private String lastName;

    // getters, setters, etc.
}

public class UserWriter {

    private final DefaultDSLContext dslContext;

    public UserWriter(DefaultDSLContext dslContext) {
        this.dslContext = dslContext;
    }

    public void create(UserDto user) {

        dslContext.insertInto(User.table, User.firstName, User.lastName)
            .values(
                DSL.param(User.firstName.getName(), user.getFirstName()),
                DSL.param(User.lastName.getName(), user.getLastName()),
            )
            .execute();
    }
}

Why use DSL.param() in values() when one can simply use the actual values ?

dslContext.insertInto(User.table, User.firstName, User.lastName)
    .values(user.getFirstName(), user.getLastName())
    .execute();

Is this just unnecessarily verbose or am I missing something?

Thanks!

CodePudding user response:

Your param() usage

Is this just unnecessarily verbose or am I missing something?

Yes, it's unnecessarily verbose in your case. Just use the version you suggested, instead.

In most cases of jOOQ's API, there's always a convenience overload for a hypothetical T|Field<T> type, so you can pass bind values (T) wherever a column expression (Field<T>) would be possible, and the bind value will be wrapped automatically in: DSL.val(value, column)

DSL.param() allows for creating named bind parameter markers where this makes sense (e.g. when exporting the SQL string to Spring or some other tool that supports named parameters). Within jOOQ, named parameters are hardly ever useful.

See also the section in the manual about bind values: https://www.jooq.org/doc/latest/manual/sql-building/bind-values/

Other verbosity

It seems that param() wasn't the only place where verbosity was cherished in your code base. jOOQ ships with a very powerful source code generator, which can generate those User and UserDto classes for you.

You get a lot of features only if you're using the code generator (other than the type safety), e.g. implicit joins.

  • Related