jOOQ 和 Java 8
适用于 ✅ 开源版 ✅ 专业版 ✅ 企业版
Java 8 引入了一系列很棒的增强功能,其中包括 lambda 表达式和新的 java.util.stream.Stream
。这些新结构与 jOOQ 的流畅 API 非常契合,如下例所示
jOOQ 和 lambda 表达式
jOOQ 的 RecordMapper API 已完全准备好支持 Java 8,这基本上意味着它是一个 SAM(单一抽象方法)类型,可以使用 lambda 表达式实例化。考虑以下示例
try (Connection c = getConnection()) { String sql = "select schema_name, is_default " + "from information_schema.schemata " + "order by schema_name"; DSL.using(c) .fetch(sql) // We can use lambda expressions to map jOOQ Records .map(rs -> new Schema( rs.getValue("SCHEMA_NAME", String.class), rs.getValue("IS_DEFAULT", boolean.class) )) // ... and then profit from the new Collection methods .forEach(System.out::println); }
上面的示例展示了 jOOQ 的 Result.map()
方法如何接收实现 RecordMapper 的 lambda 表达式,以将 jOOQ Records
映射到您的自定义类型。
jOOQ 和 Streams API
jOOQ 的 Result
类型扩展了 java.util.List
,这为 Java 8 中各种新的 Java 功能打开了访问权限。以下示例展示了将包含 INFORMATION_SCHEMA
元数据的 jOOQ Result
转换为生成 DDL 语句是多么容易
DSL.using(c) .select( COLUMNS.TABLE_NAME, COLUMNS.COLUMN_NAME, COLUMNS.TYPE_NAME ) .from(COLUMNS) .orderBy( COLUMNS.TABLE_CATALOG, COLUMNS.TABLE_SCHEMA, COLUMNS.TABLE_NAME, COLUMNS.ORDINAL_POSITION ) .fetch() // jOOQ ends here .stream() // JDK 8 Streams start here .collect(groupingBy( r -> r.getValue(COLUMNS.TABLE_NAME), LinkedHashMap::new, mapping( r -> new Column( r.getValue(COLUMNS.COLUMN_NAME), r.getValue(COLUMNS.TYPE_NAME) ), toList() ) )) .forEach( (table, columns) -> { // Just emit a CREATE TABLE statement System.out.println( "CREATE TABLE " + table + " ("); // Map each "Column" type into a String // containing the column specification, // and join them using comma and // newline. Done! System.out.println( columns.stream() .map(col -> " " + col.name + " " + col.type) .collect(Collectors.joining(",\n")) ); System.out.println(");"); } );
反馈
您对此页面有任何反馈吗? 我们很乐意听取您的意见!