Search in sources :

Example 36 with Configuration

use of org.jooq.Configuration 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 37 with Configuration

use of org.jooq.Configuration in project jOOQ by jOOQ.

the class DAOImpl method records.

private /* non-final */
List<R> records(Collection<P> objects, boolean forUpdate) {
    List<R> result = new ArrayList<>(objects.size());
    Field<?>[] pk = pk();
    DSLContext ctx;
    // [#7731] Create a Record -> POJO mapping to allow for reusing the below
    // derived Configuration for improved reflection caching.
    IdentityHashMap<R, Object> mapping = !FALSE.equals(settings().isReturnRecordToPojo()) ? new IdentityHashMap<>() : null;
    // are copied back to the relevant POJO using the RecordListener SPI
    if (mapping != null) {
        Consumer<? super RecordContext> end = c -> {
            Record record = c.record();
            // TODO: [#2536] Use mapper()
            if (record != null)
                record.into(mapping.get(record));
        };
        ctx = configuration().deriveAppending(onStoreEnd(end).onInsertEnd(end).onUpdateEnd(end).onDeleteEnd(end)).dsl();
    } else
        ctx = ctx();
    for (P object : objects) {
        R record = ctx.newRecord(table, object);
        if (mapping != null)
            mapping.put(record, object);
        if (forUpdate && pk != null)
            for (Field<?> field : pk) record.changed(field, false);
        Tools.resetChangedOnNotNull(record);
        result.add(record);
    }
    return result;
}
Also used : UniqueKey(org.jooq.UniqueKey) Arrays(java.util.Arrays) RecordMapper(org.jooq.RecordMapper) RecordListener.onStoreEnd(org.jooq.RecordListener.onStoreEnd) Table(org.jooq.Table) DAO(org.jooq.DAO) DSL.row(org.jooq.impl.DSL.row) RecordContext(org.jooq.RecordContext) Condition(org.jooq.Condition) Collections.singletonList(java.util.Collections.singletonList) ArrayList(java.util.ArrayList) Arrays.asList(java.util.Arrays.asList) DSLContext(org.jooq.DSLContext) SQLDialect(org.jooq.SQLDialect) RecordListenerProvider(org.jooq.RecordListenerProvider) UpdatableRecord(org.jooq.UpdatableRecord) FALSE(java.lang.Boolean.FALSE) Record(org.jooq.Record) IdentityHashMap(java.util.IdentityHashMap) Collection(java.util.Collection) Settings(org.jooq.conf.Settings) Field(org.jooq.Field) Consumer(java.util.function.Consumer) Configuration(org.jooq.Configuration) List(java.util.List) TableField(org.jooq.TableField) DSL.noCondition(org.jooq.impl.DSL.noCondition) EMPTY_RECORD(org.jooq.impl.Tools.EMPTY_RECORD) Optional(java.util.Optional) TRUE(java.lang.Boolean.TRUE) ArrayList(java.util.ArrayList) DSLContext(org.jooq.DSLContext) Field(org.jooq.Field) TableField(org.jooq.TableField) UpdatableRecord(org.jooq.UpdatableRecord) Record(org.jooq.Record)

Example 38 with Configuration

use of org.jooq.Configuration in project jOOQ by jOOQ.

the class CatalogMetaImpl method filterSchemas.

static final Meta filterSchemas(Configuration configuration, Set<Schema> schemas) {
    Map<Name, Catalog> c = new LinkedHashMap<>();
    Map<Name, List<Schema>> mapping = new LinkedHashMap<>();
    for (Schema schema : schemas) mapping.computeIfAbsent(nameOrDefault(schema.getCatalog()), k -> new ArrayList<>()).add(schema);
    for (Schema schema : schemas) c.computeIfAbsent(nameOrDefault(schema.getCatalog()), k -> new CatalogImpl(k) {

        @Override
        public List<Schema> getSchemas() {
            return mapping.get(getQualifiedName());
        }
    });
    return filterCatalogs(configuration, new LinkedHashSet<>(c.values())).filterSchemas(schemas::contains);
}
Also used : Arrays(java.util.Arrays) Predicate(java.util.function.Predicate) Name(org.jooq.Name) Set(java.util.Set) Table(org.jooq.Table) EMPTY_CATALOG(org.jooq.impl.Tools.EMPTY_CATALOG) Meta(org.jooq.Meta) ArrayList(java.util.ArrayList) QueryPart(org.jooq.QueryPart) LinkedHashMap(java.util.LinkedHashMap) Configuration(org.jooq.Configuration) List(java.util.List) Catalog(org.jooq.Catalog) AbstractNamed.nameOrDefault(org.jooq.impl.AbstractNamed.nameOrDefault) Map(java.util.Map) Schema(org.jooq.Schema) LinkedHashSet(java.util.LinkedHashSet) LinkedHashSet(java.util.LinkedHashSet) Schema(org.jooq.Schema) ArrayList(java.util.ArrayList) List(java.util.List) Catalog(org.jooq.Catalog) Name(org.jooq.Name) LinkedHashMap(java.util.LinkedHashMap)

Example 39 with Configuration

use of org.jooq.Configuration in project jOOQ by jOOQ.

the class LoggerListener method renderEnd.

@Override
public void renderEnd(ExecuteContext ctx) {
    if (log.isDebugEnabled()) {
        Configuration configuration = ctx.configuration();
        String newline = TRUE.equals(configuration.settings().isRenderFormatted()) ? "\n" : "";
        // [#2939] Prevent excessive logging of bind variables only in DEBUG mode, not in TRACE mode.
        if (!log.isTraceEnabled())
            configuration = configuration.deriveAppending(new BindValueAbbreviator());
        String[] batchSQL = ctx.batchSQL();
        if (ctx.query() != null) {
            // Actual SQL passed to JDBC
            log.debug("Executing query", newline + ctx.sql());
            // [#1278] DEBUG log also SQL with inlined bind values, if
            // that is not the same as the actual SQL passed to JDBC
            String inlined = DSL.using(configuration).renderInlined(ctx.query());
            if (!ctx.sql().equals(inlined))
                log.debug("-> with bind values", newline + inlined);
        } else // [#2987] Log routines
        if (ctx.routine() != null) {
            log.debug("Calling routine", newline + ctx.sql());
            String inlined = DSL.using(configuration).renderInlined(ctx.routine());
            if (!ctx.sql().equals(inlined))
                log.debug("-> with bind values", newline + inlined);
        } else if (!StringUtils.isBlank(ctx.sql())) {
            // [#1529] Batch queries should be logged specially
            if (ctx.type() == ExecuteType.BATCH)
                log.debug("Executing batch query", newline + ctx.sql());
            else
                log.debug("Executing query", newline + ctx.sql());
        } else // [#2532] Log a complete BatchMultiple query
        if (batchSQL.length > 0) {
            if (batchSQL[batchSQL.length - 1] != null)
                for (String sql : batchSQL) log.debug("Executing batch query", newline + sql);
        }
    }
}
Also used : Configuration(org.jooq.Configuration)

Example 40 with Configuration

use of org.jooq.Configuration in project jOOQ by jOOQ.

the class AbstractRoutine method registerOutParameters.

private final void registerOutParameters(ExecuteContext ctx) throws SQLException {
    Configuration c = ctx.configuration();
    CallableStatement statement = (CallableStatement) ctx.statement();
    // Note that some RDBMS do not support binding by name very well
    for (Parameter<?> parameter : getParameters0(ctx.configuration())) if (resultParameter(c, parameter))
        registerOutParameter(ctx, statement, parameter);
}
Also used : Configuration(org.jooq.Configuration) CallableStatement(java.sql.CallableStatement)

Aggregations

Configuration (org.jooq.Configuration)46 DSLContext (org.jooq.DSLContext)13 List (java.util.List)9 ArrayList (java.util.ArrayList)8 ExecuteContext (org.jooq.ExecuteContext)8 Query (org.jooq.Query)8 Record (org.jooq.Record)6 DefaultConfiguration (org.jooq.impl.DefaultConfiguration)6 Arrays (java.util.Arrays)5 SQLDialect (org.jooq.SQLDialect)5 BigInteger (java.math.BigInteger)4 OffsetDateTime (java.time.OffsetDateTime)4 Arrays.asList (java.util.Arrays.asList)4 Map (java.util.Map)4 Optional (java.util.Optional)4 DataAccessException (org.jooq.exception.DataAccessException)4 JooqLogger (org.jooq.tools.JooqLogger)4 SQLException (java.sql.SQLException)3 HashMap (java.util.HashMap)3 LinkedHashMap (java.util.LinkedHashMap)3