javajooqsqlbuilder

JAVA How to build a sql query with JOOQ step by step


In my Java code, I want to create a long query, I find JOOQ to build query and I use it without generation class but I don't find the way to build my query step by step like this:

DSLContext request = DSL.using(sqlConnection, SQLDialect.MYSQL);
request.insertInto(DSL.table("MyTable"), DSL.field("MyColumn1"), DSL.field("MyColumn2"));

// ... some code ...

request.values("hello", 98);

// ... some code ...

request.values("world", 67);

// ... some code ...

request.execute();

How to make this ?


Solution

  • You have many options.

    Stick with the DSL API

    ... and assign the intermediate types to a local variable:

    DSLContext request = DSL.using(sqlConnection, SQLDialect.MYSQL);
    InsertValuesStep2<?, Object, Object> step = request.insertInto(
        DSL.table("MyTable"), DSL.field("MyColumn1"), DSL.field("MyColumn2"));
    
    // ... some code ...
    
    step = step.values("hello", 98);
    
    // ... some code ...
    
    step = values("world", 67);
    
    // ... some code ...
    
    step.execute();
    

    Use the model API instead

    ... This kind of dynamic SQL is probably easier to implement using the model API (see also http://www.jooq.org/doc/latest/manual/sql-building/sql-statements/dsl-and-non-dsl)

    DSLContext request = DSL.using(sqlConnection, SQLDialect.MYSQL);
    InsertQuery<?> insert = request.insertQuery(DSL.table("MyTable"));
    
    // ... some code ...
    
    insert.addValue(DSL.field("MyColumn1", String.class), "hello"))
    insert.addValue(DSL.field("MyColumn1", Integer.class), 98))
    
    // ... some code ...
    
    insert.newRecord();
    insert.addValue(DSL.field("MyColumn1", String.class), "world"))
    insert.addValue(DSL.field("MyColumn1", Integer.class), 67))
    
    // ... some code ...
    
    insert.execute();
    

    Use a batch statement

    An alternative would be to send a batch of multiple individual statements to the server by using the batch API (http://www.jooq.org/doc/latest/manual/sql-execution/batch-execution). For example:

    request.batch(DSL.insertInto(
                        DSL.table("MyTable"), DSL.field("MyColumn1"), DSL.field("MyColumn2"))
                     .values((String) null, null))
           .bind("hello", 98)
           .bind("world", 67)
           .execute();
    

    ... or, in a more dynamic form:

    List<Object[]> values = new ArrayList<>();
    
    // ... some code ...
    values.add(new Object[] { "hello", 98 });
    
    // ... some code ...
    values.add(new Object[] { "world", 67});
    
    request.batch(DSL.insertInto(
                        DSL.table("MyTable"), DSL.field("MyColumn1"), DSL.field("MyColumn2"))
                     .values((String) null, null))
           .bind(values.toArray(new Object[list.size()][]))
           .execute();