Search in sources :

Example 21 with Jdbi

use of org.jdbi.v3.core.Jdbi in project tutorials by eugenp.

the class JdbiTest method whenIdentityColumn_thenInsertReturnsNewId.

@Test
public void whenIdentityColumn_thenInsertReturnsNewId() {
    Jdbi jdbi = Jdbi.create("jdbc:hsqldb:mem:testDB", "sa", "");
    jdbi.useHandle(handle -> {
        handle.execute("create table PROJECT_2 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))");
        Update update = handle.createUpdate("INSERT INTO PROJECT_2 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')");
        ResultBearing generatedKeys = update.executeAndReturnGeneratedKeys();
        assertEquals(0, generatedKeys.mapToMap().findOnly().get("id"));
        update = handle.createUpdate("INSERT INTO PROJECT_2 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')");
        assertEquals(1, generatedKeys.mapToMap().findOnly().get("id"));
    });
}
Also used : Jdbi(org.jdbi.v3.core.Jdbi) ResultBearing(org.jdbi.v3.core.result.ResultBearing) Update(org.jdbi.v3.core.statement.Update) Test(org.junit.Test)

Example 22 with Jdbi

use of org.jdbi.v3.core.Jdbi in project SimpleFlatMapper by arnaudroger.

the class RowMapperFactoryTest method testMapToDbObject.

@Test
public void testMapToDbObject() throws Exception {
    Jdbi dbi = Jdbi.create(DbHelper.getHsqlDataSource());
    dbi.installPlugins();
    Handle handle = dbi.open();
    try {
        DbObject dbObject = handle.createQuery(DbHelper.TEST_DB_OBJECT_QUERY).mapTo(DbObject.class).findFirst().get();
        DbHelper.assertDbObjectMapping(dbObject);
    } finally {
        handle.close();
    }
}
Also used : Jdbi(org.jdbi.v3.core.Jdbi) DbObject(org.simpleflatmapper.test.beans.DbObject) Handle(org.jdbi.v3.core.Handle) Test(org.junit.Test)

Example 23 with Jdbi

use of org.jdbi.v3.core.Jdbi in project jdbi by jdbi.

the class OnDemandExtensions method create.

static <E> E create(Jdbi db, Class<E> extensionType) {
    ThreadLocal<E> threadExtension = new ThreadLocal<>();
    InvocationHandler handler = (proxy, method, args) -> {
        if (EQUALS_METHOD.equals(method)) {
            return proxy == args[0];
        }
        if (HASHCODE_METHOD.equals(method)) {
            return System.identityHashCode(proxy);
        }
        if (TOSTRING_METHOD.equals(method)) {
            return extensionType + "@" + Integer.toHexString(System.identityHashCode(proxy));
        }
        if (threadExtension.get() != null) {
            return invoke(threadExtension.get(), method, args);
        }
        return db.withExtension(extensionType, extension -> JdbiThreadLocals.invokeInContext(threadExtension, extension, () -> invoke(extension, method, args)));
    };
    return extensionType.cast(Proxy.newProxyInstance(extensionType.getClassLoader(), new Class[] { extensionType }, handler));
}
Also used : Proxy(java.lang.reflect.Proxy) JdbiThreadLocals(org.jdbi.v3.core.internal.JdbiThreadLocals) MethodHandles(java.lang.invoke.MethodHandles) InvocationHandler(java.lang.reflect.InvocationHandler) Method(java.lang.reflect.Method) InvocationHandler(java.lang.reflect.InvocationHandler)

Example 24 with Jdbi

use of org.jdbi.v3.core.Jdbi in project jdbi by jdbi.

the class Jdbi method open.

/**
 * Obtain a Handle to the data source wrapped by this Jdbi instance.
 * You own this expensive resource and are required to close it or
 * risk leaks.  Using a {@code try-with-resources} block is recommended.
 *
 * @return an open Handle instance
 * @see #useHandle(HandleConsumer)
 * @see #withHandle(HandleCallback)
 */
public Handle open() {
    try {
        final long start = System.nanoTime();
        Connection conn = connectionFactory.openConnection();
        final long stop = System.nanoTime();
        for (JdbiPlugin p : plugins) {
            conn = p.customizeConnection(conn);
        }
        StatementBuilder cache = statementBuilderFactory.get().createStatementBuilder(conn);
        Handle h = new Handle(config.createCopy(), transactionhandler.get(), cache, conn);
        for (JdbiPlugin p : plugins) {
            h = p.customizeHandle(h);
        }
        LOG.trace("Jdbi [{}] obtain handle [{}] in {}ms", this, h, (stop - start) / 1000000L);
        return h;
    } catch (SQLException e) {
        throw new ConnectionException(e);
    }
}
Also used : SQLException(java.sql.SQLException) JdbiPlugin(org.jdbi.v3.core.spi.JdbiPlugin) DefaultStatementBuilder(org.jdbi.v3.core.statement.DefaultStatementBuilder) StatementBuilder(org.jdbi.v3.core.statement.StatementBuilder) Connection(java.sql.Connection)

Example 25 with Jdbi

use of org.jdbi.v3.core.Jdbi in project jdbi by jdbi.

the class TestVendorArrays method testHsqlDb.

@Test
public void testHsqlDb() {
    Jdbi db = Jdbi.create("jdbc:hsqldb:mem:" + UUID.randomUUID());
    init(db);
    try (Handle handle = db.open()) {
        handle.execute("create table player_stats (" + "name varchar(64) primary key, " + "seasons varchar(36) array, " + "points int array)");
        handle.createUpdate("insert into player_stats (name,seasons,points) values (?,?,?)").bind(0, "Jack Johnson").bind(1, new String[] { "2013-2014", "2014-2015", "2015-2016" }).bind(2, new Integer[] { 42, 51, 50 }).execute();
        String[] seasons = handle.createQuery("select seasons from player_stats where name=:name").bind("name", "Jack Johnson").mapTo(String[].class).findOnly();
        assertThat(seasons).containsExactly("2013-2014", "2014-2015", "2015-2016");
    }
}
Also used : Jdbi(org.jdbi.v3.core.Jdbi) Handle(org.jdbi.v3.core.Handle) Test(org.junit.Test)

Aggregations

Jdbi (org.jdbi.v3.core.Jdbi)36 Test (org.junit.Test)32 Handle (org.jdbi.v3.core.Handle)11 Something (org.jdbi.v3.core.Something)6 SomethingMapper (org.jdbi.v3.core.mapper.SomethingMapper)5 Query (org.jdbi.v3.core.statement.Query)5 Before (org.junit.Before)5 SQLException (java.sql.SQLException)4 Update (org.jdbi.v3.core.statement.Update)3 SqlObjectPlugin (org.jdbi.v3.sqlobject.SqlObjectPlugin)3 BeforeClass (org.junit.BeforeClass)3 Method (java.lang.reflect.Method)2 Stream (java.util.stream.Stream)2 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)2 H2DatabaseRule (org.jdbi.v3.core.rule.H2DatabaseRule)2 DefaultStatementBuilder (org.jdbi.v3.core.statement.DefaultStatementBuilder)2 SqlObjects (org.jdbi.v3.sqlobject.SqlObjects)2 Bind (org.jdbi.v3.sqlobject.customizer.Bind)2 SqlQuery (org.jdbi.v3.sqlobject.statement.SqlQuery)2 Rule (org.junit.Rule)2