Search in sources :

Example 1 with BookRecord

use of org.jooq.example.db.h2.tables.records.BookRecord in project SimpleFlatMapper by arnaudroger.

the class Example_One_To_Many method authorsAndBooks.

@Test
public void authorsAndBooks() throws SQLException {
    // All we need to execute a query is provide it with a connection and then
    // call fetch() on it.
    Tools.title("Selecting authorsAndBooks");
    JdbcMapper<Tuple2<AuthorRecord, List<BookRecord>>> mapper = JdbcMapperFactory.newInstance().addKeys("id").newMapper(new TypeReference<Tuple2<AuthorRecord, List<BookRecord>>>() {
    });
    try (ResultSet rs = DSL.using(connection()).select(AUTHOR.ID, AUTHOR.FIRST_NAME, AUTHOR.LAST_NAME, AUTHOR.DATE_OF_BIRTH, BOOK.ID, BOOK.TITLE).from(AUTHOR).leftJoin(BOOK).on(BOOK.AUTHOR_ID.eq(AUTHOR.ID)).orderBy(AUTHOR.ID).fetchResultSet()) {
        mapper.stream(rs).forEach(Tools::print);
    }
}
Also used : Tuple2(org.jooq.lambda.tuple.Tuple2) ResultSet(java.sql.ResultSet) Tools(org.jooq.academy.tools.Tools) BookRecord(org.jooq.example.db.h2.tables.records.BookRecord) Test(org.junit.Test)

Example 2 with BookRecord

use of org.jooq.example.db.h2.tables.records.BookRecord in project SimpleFlatMapper by arnaudroger.

the class Example_One_To_Many method authorsAndBooksAndBookStore.

@Test
public void authorsAndBooksAndBookStore() throws SQLException {
    // All we need to execute a query is provide it with a connection and then
    // call fetch() on it.
    Tools.title("Selecting authorsAndBooksAndBookStore");
    JdbcMapper<Tuple2<AuthorRecord, List<Tuple2<BookRecord, List<BookToBookStoreRecord>>>>> mapper = JdbcMapperFactory.newInstance().addKeys("ID", "BOOK_STORE_NAME").newMapper(new TypeReference<Tuple2<AuthorRecord, List<Tuple2<BookRecord, List<BookToBookStoreRecord>>>>>() {
    });
    try (ResultSet rs = DSL.using(connection()).select(AUTHOR.ID, AUTHOR.FIRST_NAME, AUTHOR.LAST_NAME, AUTHOR.DATE_OF_BIRTH, BOOK.ID, BOOK.TITLE, BOOK_TO_BOOK_STORE.BOOK_STORE_NAME, BOOK_TO_BOOK_STORE.STOCK).from(AUTHOR).leftJoin(BOOK).on(BOOK.AUTHOR_ID.eq(AUTHOR.ID)).leftJoin(BOOK_TO_BOOK_STORE).on(BOOK_TO_BOOK_STORE.BOOK_ID.eq(BOOK.ID)).orderBy(AUTHOR.ID).fetchResultSet()) {
        mapper.stream(rs).forEach(Tools::print);
    }
}
Also used : Tuple2(org.jooq.lambda.tuple.Tuple2) ResultSet(java.sql.ResultSet) Tools(org.jooq.academy.tools.Tools) BookToBookStoreRecord(org.jooq.example.db.h2.tables.records.BookToBookStoreRecord) Test(org.junit.Test)

Example 3 with BookRecord

use of org.jooq.example.db.h2.tables.records.BookRecord in project jOOQ by jOOQ.

the class SparkCRUD method main.

public static void main(String[] args) throws Exception {
    final BasicDataSource ds = new BasicDataSource();
    final Properties properties = new Properties();
    properties.load(SparkCRUD.class.getResourceAsStream("/config.properties"));
    ds.setDriverClassName(properties.getProperty("db.driver"));
    ds.setUrl(properties.getProperty("db.url"));
    ds.setUsername(properties.getProperty("db.username"));
    ds.setPassword(properties.getProperty("db.password"));
    final ConnectionProvider cp = new DataSourceConnectionProvider(ds);
    final Configuration configuration = new DefaultConfiguration().set(cp).set(SQLDialect.H2).set(new ThreadLocalTransactionProvider(cp, true));
    final DSLContext ctx = DSL.using(configuration);
    final JSONFormat format = new JSONFormat().format(true).header(false).recordFormat(RecordFormat.OBJECT);
    // 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) -> {
        return ctx.transactionResult(() -> {
            AuthorRecord author = upsertAuthor(ctx, request);
            BookRecord book = ctx.newRecord(BOOK);
            book.setAuthorId(author.getId());
            book.setTitle(request.queryParams("title"));
            book.store();
            // 201 Created
            response.status(201);
            return book.formatJSON(format);
        });
    });
    // 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 book.formatJSON(format);
        } else {
            // 404 Not found
            response.status(404);
            return "{\"error\":\"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) -> {
        return ctx.transactionResult(() -> {
            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.formatJSON(format);
            } else {
                // 404 Not found
                response.status(404);
                return "{\"error\":\"Book not found\"}";
            }
        });
    });
    // Deletes the book resource for the provided id
    delete("/books/:id", (request, response) -> {
        return ctx.transactionResult(() -> {
            BookRecord book = ctx.deleteFrom(BOOK).where(BOOK.ID.eq(BOOK.ID.getDataType().convert(request.params(":id")))).returning().fetchOne();
            if (book != null) {
                return book.formatJSON(format);
            } else {
                // 404 Not found
                response.status(404);
                return "{\"error\":\"Book not found\"}";
            }
        });
    });
    // Gets all available book resources
    get("/books", (request, response) -> {
        return ctx.select(BOOK.ID, BOOK.TITLE).from(BOOK).fetch().formatJSON(format);
    });
}
Also used : DefaultConfiguration(org.jooq.impl.DefaultConfiguration) Configuration(org.jooq.Configuration) DataSourceConnectionProvider(org.jooq.impl.DataSourceConnectionProvider) ThreadLocalTransactionProvider(org.jooq.impl.ThreadLocalTransactionProvider) DSLContext(org.jooq.DSLContext) DefaultConfiguration(org.jooq.impl.DefaultConfiguration) Properties(java.util.Properties) JSONFormat(org.jooq.JSONFormat) ConnectionProvider(org.jooq.ConnectionProvider) DataSourceConnectionProvider(org.jooq.impl.DataSourceConnectionProvider) AuthorRecord(org.jooq.example.db.h2.tables.records.AuthorRecord) BookRecord(org.jooq.example.db.h2.tables.records.BookRecord) BasicDataSource(org.apache.commons.dbcp.BasicDataSource)

Example 4 with BookRecord

use of org.jooq.example.db.h2.tables.records.BookRecord in project jOOQ by jOOQ.

the class Example_2_2_OptimisticLocking method run.

@Test
public void run() throws SQLException {
    Connection connection = connection();
    DSLContext dsl = DSL.using(connection, new Settings().withExecuteWithOptimisticLocking(true));
    try {
        Tools.title("Applying optimistic locking");
        BookRecord book1 = dsl.selectFrom(BOOK).where(BOOK.ID.eq(1)).fetchOne();
        BookRecord book2 = dsl.selectFrom(BOOK).where(BOOK.ID.eq(1)).fetchOne();
        book1.setTitle("New Title");
        book1.store();
        book2.setTitle("Another Title");
        book2.store();
    } catch (DataChangedException expected) {
        expected.printStackTrace();
    } finally // Don't store the changes
    {
        connection.rollback();
    }
}
Also used : DataChangedException(org.jooq.exception.DataChangedException) Connection(java.sql.Connection) DSLContext(org.jooq.DSLContext) BookRecord(org.jooq.example.db.h2.tables.records.BookRecord) Settings(org.jooq.conf.Settings) Test(org.junit.Test)

Aggregations

BookRecord (org.jooq.example.db.h2.tables.records.BookRecord)3 Test (org.junit.Test)3 ResultSet (java.sql.ResultSet)2 DSLContext (org.jooq.DSLContext)2 Tools (org.jooq.academy.tools.Tools)2 Tuple2 (org.jooq.lambda.tuple.Tuple2)2 Connection (java.sql.Connection)1 Properties (java.util.Properties)1 BasicDataSource (org.apache.commons.dbcp.BasicDataSource)1 Configuration (org.jooq.Configuration)1 ConnectionProvider (org.jooq.ConnectionProvider)1 JSONFormat (org.jooq.JSONFormat)1 Settings (org.jooq.conf.Settings)1 AuthorRecord (org.jooq.example.db.h2.tables.records.AuthorRecord)1 BookToBookStoreRecord (org.jooq.example.db.h2.tables.records.BookToBookStoreRecord)1 DataChangedException (org.jooq.exception.DataChangedException)1 DataSourceConnectionProvider (org.jooq.impl.DataSourceConnectionProvider)1 DefaultConfiguration (org.jooq.impl.DefaultConfiguration)1 ThreadLocalTransactionProvider (org.jooq.impl.ThreadLocalTransactionProvider)1