[#4307] Add an example using the Spark Framework

This commit is contained in:
lukaseder 2015-05-26 16:24:27 +02:00
parent 3a91f13e08
commit 501caf4d02
10 changed files with 542 additions and 0 deletions

View File

@ -0,0 +1,2 @@
/target
/*.iml

View File

@ -0,0 +1,22 @@
Copyright (c) 2009-2015, Data Geekery GmbH (http://www.datageekery.com)
All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Other licenses:
-----------------------------------------------------------------------------
Commercial licenses for this work are available. These replace the above
ASL 2.0 and offer limited warranties, support, maintenance, and commercial
database integrations.
For more information, please visit: http://www.jooq.org/licenses

View File

@ -0,0 +1,16 @@
Thanks for downloading jOOQ.
Please visit http://www.jooq.org for more information.
To install and run this example, please check out the complete jOOQ repository first, and use Maven to install the latest SNAPSHOT version of jOOQ:
```
$ pwd
/path/to/checkout/dir
$ ls
jOOQ jOOQ-meta jOOQ-codegen ...
$ mvn clean install
...
$ cd jOOQ-examples/jOOQ-javafx-example
...
$ mvn clean install
```

View File

@ -0,0 +1,224 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.jooq</groupId>
<artifactId>jooq-spark-example</artifactId>
<version>1.0</version>
<name>jOOQ Spark Example</name>
<licenses>
<license>
<name>Apache License, Version 2.0</name>
<url>http://www.jooq.org/inc/LICENSE.txt</url>
<distribution>repo</distribution>
</license>
</licenses>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<org.springframework.version>3.2.6.RELEASE</org.springframework.version>
<org.jooq.version>3.6.1</org.jooq.version>
<org.h2.version>1.4.181</org.h2.version>
</properties>
<dependencies>
<!-- Database access -->
<dependency>
<groupId>org.jooq</groupId>
<artifactId>jooq</artifactId>
<version>${org.jooq.version}</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${org.h2.version}</version>
</dependency>
<!-- Spark framework -->
<dependency>
<groupId>com.sparkjava</groupId>
<artifactId>spark-core</artifactId>
<version>2.2</version>
</dependency>
<!-- Logging -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.5</version>
</dependency>
<!-- Testing -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<type>jar</type>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<!-- The resources element will replace available properties in all matching
resources. We use this to provide H2 connection configuration to various
configuration elements -->
<resources>
<resource>
<filtering>true</filtering>
<directory>src/main/resources</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<fork>true</fork>
<maxmem>1024m</maxmem>
<meminitial>256m</meminitial>
<encoding>UTF-8</encoding>
<source>1.8</source>
<target>1.8</target>
<debug>true</debug>
<debuglevel>lines,vars,source</debuglevel>
<!-- [#2413] Make compiler warnings a bit more visible
But don't fail (yet) -->
<compilerArgs>
<arg>-Xlint:varargs</arg>
</compilerArgs>
</configuration>
</plugin>
<!-- We're using the properties plugin to load external properties into Maven.
See this excellent blog post for an explanation:
http://www.petrikainulainen.net/programming/tips-and-tricks/creating-profile-specific-configuration-files-with-maven/ -->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>properties-maven-plugin</artifactId>
<version>1.0-alpha-2</version>
<executions>
<execution>
<phase>initialize</phase>
<goals>
<goal>read-project-properties</goal>
</goals>
<configuration>
<files>
<file>src/main/resources/config.properties</file>
</files>
</configuration>
</execution>
</executions>
</plugin>
<!-- The H2 test schema is loaded here -->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>sql-maven-plugin</artifactId>
<version>1.5</version>
<configuration>
<skip>${maven.test.skip}</skip>
<forkMode>always</forkMode>
</configuration>
<executions>
<execution>
<id>create-database-postgres</id>
<phase>generate-sources</phase>
<goals>
<goal>execute</goal>
</goals>
<configuration>
<driver>${db.driver}</driver>
<url>${db.url}</url>
<username>${db.username}</username>
<password>${db.password}</password>
<autocommit>true</autocommit>
<srcFiles>
<srcFile>src/main/resources/db-h2.sql</srcFile>
</srcFiles>
</configuration>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${org.h2.version}</version>
</dependency>
</dependencies>
</plugin>
<!-- The jOOQ code generator plugin -->
<plugin>
<groupId>org.jooq</groupId>
<artifactId>jooq-codegen-maven</artifactId>
<version>${org.jooq.version}</version>
<executions>
<execution>
<id>generate-h2</id>
<phase>generate-sources</phase>
<goals>
<goal>generate</goal>
</goals>
<configuration>
<jdbc>
<driver>${db.driver}</driver>
<url>${db.url}</url>
<user>${db.username}</user>
<password>${db.password}</password>
</jdbc>
<generator>
<database>
<inputSchema>PUBLIC</inputSchema>
</database>
<target>
<packageName>org.jooq.example.db.h2</packageName>
<directory>target/generated-sources/jooq-h2</directory>
</target>
</generator>
</configuration>
</execution>
</executions>
</plugin>
<!-- Run the JavaFX application right after building -->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<executions>
<execution>
<id>run-example</id>
<phase>install</phase>
<goals>
<goal>java</goal>
</goals>
<configuration>
<mainClass>org.jooq.example.spark.SparkCRUD</mainClass>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,181 @@
/**
* Copyright (c) 2009-2015, Data Geekery GmbH (http://www.datageekery.com)
* All rights reserved.
*
* This work is dual-licensed
* - under the Apache Software License 2.0 (the "ASL")
* - under the jOOQ License and Maintenance Agreement (the "jOOQ License")
* =============================================================================
* You may choose which license applies to you:
*
* - If you're using this work with Open Source databases, you may choose
* either ASL or jOOQ License.
* - If you're using this work with at least one commercial database, you must
* choose jOOQ License
*
* For more information, please visit http://www.jooq.org/licenses
*
* Apache Software License 2.0:
* -----------------------------------------------------------------------------
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* jOOQ License and Maintenance Agreement:
* -----------------------------------------------------------------------------
* Data Geekery grants the Customer the non-exclusive, timely limited and
* non-transferable license to install and use the Software under the terms of
* the jOOQ License and Maintenance Agreement.
*
* This library is distributed with a LIMITED WARRANTY. See the jOOQ License
* and Maintenance Agreement for more details: http://www.jooq.org/licensing
*/
package org.jooq.example.spark;
import static org.jooq.example.db.h2.Tables.AUTHOR;
import static org.jooq.example.db.h2.Tables.BOOK;
import static spark.Spark.delete;
import static spark.Spark.get;
import static spark.Spark.post;
import static spark.Spark.put;
import java.util.Properties;
import java.util.stream.Collectors;
import org.jooq.DSLContext;
import org.jooq.Record2;
import org.jooq.example.db.h2.tables.records.AuthorRecord;
import org.jooq.example.db.h2.tables.records.BookRecord;
import org.jooq.impl.DSL;
import spark.Request;
/**
* A simple CRUD example showing howto create, get, update and delete book resources.
*/
public class SparkCRUD {
public static void main(String[] args) throws Exception {
final Properties properties = new Properties();
properties.load(SparkCRUD.class.getResourceAsStream("/config.properties"));
Class.forName(properties.getProperty("db.driver"));
final DSLContext ctx = DSL.using(
properties.getProperty("db.url"),
properties.getProperty("db.username"),
properties.getProperty("db.password")
);
// Creates a new book resource, will return the ID to the created resource
// author and title are sent as query parameters e.g. /books?author=Foo&title=Bar
post("/books", (request, response) -> {
AuthorRecord author = upsertAuthor(ctx, request);
BookRecord book = ctx.newRecord(BOOK);
book.setAuthorId(author.getId());
book.setTitle(request.queryParams("title"));
book.store();
response.status(201); // 201 Created
return book.getId();
});
// Gets the book resource for the provided id
get("/books/:id", (request, response) -> {
Record2<String, String> book = ctx
.select(BOOK.TITLE, AUTHOR.NAME)
.from(BOOK)
.join(AUTHOR).on(BOOK.AUTHOR_ID.eq(AUTHOR.ID))
.where(BOOK.ID.eq(BOOK.ID.getDataType().convert(request.params(":id"))))
.fetchOne();
if (book != null) {
return "Title: " + book.value1() + ", Author: " + book.value2();
}
else {
response.status(404); // 404 Not found
return "Book not found";
}
});
// Updates the book resource for the provided id with new information
// author and title are sent as query parameters e.g. /books/<id>?author=Foo&title=Bar
put("/books/:id", (request, response) -> {
BookRecord book = ctx
.selectFrom(BOOK)
.where(BOOK.ID.eq(BOOK.ID.getDataType().convert(request.params(":id"))))
.fetchOne();
if (book != null) {
AuthorRecord author = upsertAuthor(ctx, request);
String newAuthor = request.queryParams("author");
String newTitle = request.queryParams("title");
if (newAuthor != null) {
book.setAuthorId(author.getId());
}
if (newTitle != null) {
book.setTitle(newTitle);
}
book.update();
return "Book with id '" + book.getId() + "' updated";
}
else {
response.status(404); // 404 Not found
return "Book not found";
}
});
// Deletes the book resource for the provided id
delete("/books/:id", (request, response) -> {
BookRecord book = ctx
.deleteFrom(BOOK)
.where(BOOK.ID.eq(BOOK.ID.getDataType().convert(request.params(":id"))))
.returning()
.fetchOne();
if (book != null) {
return "Book with id '" + book.getId() + "' deleted";
}
else {
response.status(404); // 404 Not found
return "Book not found";
}
});
// Gets all available book resources (id's)
get("/books", (request, response) -> {
return ctx
.select(BOOK.ID)
.from(BOOK)
.fetch(BOOK.ID)
.stream()
.map(Object::toString)
.collect(Collectors.joining(" "));
});
}
private static AuthorRecord upsertAuthor(final DSLContext ctx, Request request) {
AuthorRecord author = ctx
.selectFrom(AUTHOR)
.where(AUTHOR.NAME.eq(request.queryParams("author")))
.fetchOne();
if (author == null)
author = ctx.newRecord(AUTHOR);
author.setName(request.queryParams("author"));
author.store();
return author;
}
}

View File

@ -0,0 +1,22 @@
Copyright (c) 2009-2015, Data Geekery GmbH (http://www.datageekery.com)
All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Other licenses:
-----------------------------------------------------------------------------
Commercial licenses for this work are available. These replace the above
ASL 2.0 and offer limited warranties, support, maintenance, and commercial
database integrations.
For more information, please visit: http://www.jooq.org/licenses

View File

@ -0,0 +1,2 @@
Thanks for downloading jOOQ.
Please visit http://www.jooq.org for more information.

View File

@ -0,0 +1,11 @@
#Database Configuration
db.driver=org.h2.Driver
db.url=jdbc:h2:~/jooq-spark-example
db.username=sa
db.password=
#jOOQ Configuration
jooq.sql.dialect=H2
#DB Schema
db.schema.script=db-h2.sql

View File

@ -0,0 +1,26 @@
DROP TABLE IF EXISTS book;
DROP TABLE IF EXISTS author;
CREATE TABLE author (
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(50),
CONSTRAINT pk_t_author PRIMARY KEY (ID)
);
CREATE TABLE book (
id INT NOT NULL AUTO_INCREMENT,
author_id INT NOT NULL,
title VARCHAR(400) NOT NULL,
CONSTRAINT pk_t_book PRIMARY KEY (id),
CONSTRAINT fk_t_book_author_id FOREIGN KEY (author_id) REFERENCES author(id) ON DELETE CASCADE,
);
INSERT INTO author VALUES (DEFAULT, 'George Orwell');
INSERT INTO author VALUES (DEFAULT, 'Paulo Coelho');
INSERT INTO book VALUES (DEFAULT, 1, '1984');
INSERT INTO book VALUES (DEFAULT, 1, 'Animal Farm');
INSERT INTO book VALUES (DEFAULT, 2, 'O Alquimista');
INSERT INTO book VALUES (DEFAULT, 2, 'Brida');

View File

@ -0,0 +1,36 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration PUBLIC "-//APACHE//DTD LOG4J 1.2//EN" "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="console" class="org.apache.log4j.ConsoleAppender">
<param name="Target" value="System.out"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{ABSOLUTE} %5p [%-70c{4}] - %m%n" />
</layout>
</appender>
<logger name="org.springframework.core">
<level value="info"/>
</logger>
<logger name="org.springframework.beans">
<level value="info"/>
</logger>
<logger name="org.springframework.context">
<level value="info"/>
</logger>
<logger name="org.springframework.web">
<level value="info"/>
</logger>
<logger name="org.jooq.impl">
<level value="debug"/>
</logger>
<root>
<priority value="debug"/>
<appender-ref ref="console"/>
</root>
</log4j:configuration>