Java 8和JOOQ結合寫

Java 8引入了大量的增強,其中lambda表達式和新的 java.util.stream.Stream.。這些新的構造與Jooq流利的API對齊得很好,可以從下面的例子中看到:

jOOQ and lambda 表達式

JOOQ官方網站:https://www.jooq.org

jOOQ的RecordMapper API是完全Java-8-ready,這基本上意味著它是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);

}

DSL.using(c)

.select(

COUNTRIES.YEAR,

COUNTRIES.CODE,

COUNTRIES.GOVT_DEBT)

.from(COUNTRIES)

.join(

table(

select(COUNTRIES.CODE, avg(COUNTRIES.GOVT_DEBT).as("avg"))

.from(COUNTRIES)

.groupBy(COUNTRIES.CODE)

).as("c1")

)

.on(COUNTRIES.CODE.eq(field(name("c1", COUNTRIES.CODE.getName()), String.class)))

// order countries by their average projected value

.orderBy(

field(name("avg")),

COUNTRIES.CODE,

COUNTRIES.YEAR)

上面的示例顯示了jOOQ的Ressult.map()方法如何接收lambda表達式,該表達式實現RecordMapper以將jOOQ記錄映射到定製類型。

jOOQ and the 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(");");

}

);

上面的示例在本博客文章中進行了更深入的解釋:http://blog.jooq.org/2014/04/11/java-8-friday-no-more-.-for-orms/。

Java 8 is the future, and with jOOQ, Java 8, and the Streams API, you can write powerful data transformation APIs. I hope we got you as excited as we are!


分享到:


相關文章: