在我的Java代码中,我想创建一个长查询,我发现JOOQ构建查询并且我在没有生成类的情况下使用它但是我找不到像这样逐步构建查询的方法:
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();
如何制作?
答案 0 :(得分:3)
你有很多选择。
...并将中间类型分配给局部变量:
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();
...使用模型API可以更容易地实现这种动态SQL(另请参阅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();
另一种方法是使用批处理API(http://www.jooq.org/doc/latest/manual/sql-execution/batch-execution)向服务器发送一批多个单独的语句。例如:
request.batch(DSL.insertInto(
DSL.table("MyTable"), DSL.field("MyColumn1"), DSL.field("MyColumn2"))
.values((String) null, null))
.bind("hello", 98)
.bind("world", 67)
.execute();
......或者,以更动态的形式:
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();