Search in sources :

Example 91 with Handle

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

the class TestNamedParams method testBeanPropertyNestedBinding.

@Test
public void testBeanPropertyNestedBinding() throws Exception {
    Handle h = dbRule.openHandle();
    Something thing = new Something(0, "Keith");
    assertThat(h.createUpdate("insert into something (id, name) values (:my.nested.id, :my.nested.name)").bindBean("my", new Object() {

        @SuppressWarnings("unused")
        public Something getNested() {
            return thing;
        }
    }).execute()).isEqualTo(1);
    assertThat(h.select("select * from something where id = ?", thing.getId()).mapToBean(Something.class).findOnly()).isEqualTo(thing);
}
Also used : Something(org.jdbi.v3.core.Something) Handle(org.jdbi.v3.core.Handle) Test(org.junit.Test)

Example 92 with Handle

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

the class TestNamedParams method testInsert.

@Test
public void testInsert() throws Exception {
    Handle h = dbRule.openHandle();
    Update insert = h.createUpdate("insert into something (id, name) values (:id, :name)");
    insert.bind("id", 1);
    insert.bind("name", "Brian");
    int count = insert.execute();
    assertThat(count).isEqualTo(1);
}
Also used : Update(org.jdbi.v3.core.statement.Update) Handle(org.jdbi.v3.core.Handle) Test(org.junit.Test)

Example 93 with Handle

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

the class FiveMinuteTourTest method setUp.

@Before
public void setUp() {
    // tag::createJdbi[]
    // H2 in-memory database
    Jdbi jdbi = Jdbi.create("jdbc:h2:mem:test");
    // end::createJdbi[]
    // shared handle to keep database open
    this.jdbi = jdbi;
    this.handle = jdbi.open();
    // tag::useHandle[]
    jdbi.useHandle(handle -> {
        handle.execute("create table contacts (id int primary key, name varchar(100))");
        handle.execute("insert into contacts (id, name) values (?, ?)", 1, "Alice");
        handle.execute("insert into contacts (id, name) values (?, ?)", 2, "Bob");
    });
    // end::useHandle[]
    // tag::withHandle[]
    List<String> names = jdbi.withHandle(handle -> handle.createQuery("select name from contacts").mapTo(String.class).list());
    assertThat(names).contains("Alice", "Bob");
// end::withHandle[]
}
Also used : Jdbi(org.jdbi.v3.core.Jdbi) Before(org.junit.Before)

Example 94 with Handle

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

the class IntroductionTest method core.

@Test
public void core() {
    // tag::core[]
    // (H2 in-memory database)
    Jdbi jdbi = Jdbi.create("jdbc:h2:mem:test");
    List<User> users = jdbi.withHandle(handle -> {
        handle.execute("CREATE TABLE user (id INTEGER PRIMARY KEY, name VARCHAR)");
        // Inline positional parameters
        handle.execute("INSERT INTO user(id, name) VALUES (?, ?)", 0, "Alice");
        // Positional parameters
        handle.createUpdate("INSERT INTO user(id, name) VALUES (?, ?)").bind(0, // 0-based parameter indexes
        1).bind(1, "Bob").execute();
        // Named parameters
        handle.createUpdate("INSERT INTO user(id, name) VALUES (:id, :name)").bind("id", 2).bind("name", "Clarice").execute();
        // Named parameters from bean properties
        handle.createUpdate("INSERT INTO user(id, name) VALUES (:id, :name)").bindBean(new User(3, "David")).execute();
        // Easy mapping to any type
        return handle.createQuery("SELECT * FROM user ORDER BY name").mapToBean(User.class).list();
    });
    assertThat(users).containsExactly(new User(0, "Alice"), new User(1, "Bob"), new User(2, "Clarice"), new User(3, "David"));
// end::core[]
}
Also used : Jdbi(org.jdbi.v3.core.Jdbi) Test(org.junit.Test)

Example 95 with Handle

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

the class TransactionTest method serializableTransaction.

@Test
public void serializableTransaction() throws Exception {
    // tag::serializable[]
    // Automatically rerun transactions
    db.setTransactionHandler(new SerializableTransactionRunner());
    // Set up some values
    BiConsumer<Handle, Integer> insert = (h, i) -> h.execute("INSERT INTO ints(value) VALUES(?)", i);
    handle.execute("CREATE TABLE ints (value INTEGER)");
    insert.accept(handle, 10);
    insert.accept(handle, 20);
    // Run the following twice in parallel, and synchronize
    ExecutorService executor = Executors.newCachedThreadPool();
    CountDownLatch latch = new CountDownLatch(2);
    Callable<Integer> sumAndInsert = () -> db.inTransaction(TransactionIsolationLevel.SERIALIZABLE, h -> {
        // Both read initial state of table
        int sum = h.select("SELECT sum(value) FROM ints").mapTo(int.class).findOnly();
        // First time through, make sure neither transaction writes until both have read
        latch.countDown();
        latch.await();
        // Now do the write.
        insert.accept(h, sum);
        return sum;
    });
    // Both of these would calculate 10 + 20 = 30, but that violates serialization!
    Future<Integer> result1 = executor.submit(sumAndInsert);
    Future<Integer> result2 = executor.submit(sumAndInsert);
    // One of the transactions gets 30, the other will abort and automatically rerun.
    // On the second attempt it will compute 10 + 20 + 30 = 60, seeing the update from its sibling.
    // This assertion fails under any isolation level below SERIALIZABLE!
    assertThat(result1.get() + result2.get()).isEqualTo(30 + 60);
    executor.shutdown();
// end::serializable[]
}
Also used : Arrays(java.util.Arrays) Transaction(org.jdbi.v3.sqlobject.transaction.Transaction) SqlUpdate(org.jdbi.v3.sqlobject.statement.SqlUpdate) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) SqlObject(org.jdbi.v3.sqlobject.SqlObject) Callable(java.util.concurrent.Callable) TransactionException(org.jdbi.v3.core.transaction.TransactionException) Future(java.util.concurrent.Future) Handle(org.jdbi.v3.core.Handle) BiConsumer(java.util.function.BiConsumer) ClassRule(org.junit.ClassRule) JdbiRule(org.jdbi.v3.testing.JdbiRule) ExpectedException(org.junit.rules.ExpectedException) ExecutorService(java.util.concurrent.ExecutorService) SqlQuery(org.jdbi.v3.sqlobject.statement.SqlQuery) Before(org.junit.Before) Jdbi(org.jdbi.v3.core.Jdbi) TransactionIsolationLevel(org.jdbi.v3.core.transaction.TransactionIsolationLevel) Test(org.junit.Test) SerializableTransactionRunner(org.jdbi.v3.core.transaction.SerializableTransactionRunner) Executors(java.util.concurrent.Executors) CountDownLatch(java.util.concurrent.CountDownLatch) Rule(org.junit.Rule) Optional(java.util.Optional) User(jdbi.doc.ResultsTest.User) ConstructorMapper(org.jdbi.v3.core.mapper.reflect.ConstructorMapper) PostgresDbRule(org.jdbi.v3.postgres.PostgresDbRule) ExecutorService(java.util.concurrent.ExecutorService) SerializableTransactionRunner(org.jdbi.v3.core.transaction.SerializableTransactionRunner) CountDownLatch(java.util.concurrent.CountDownLatch) Handle(org.jdbi.v3.core.Handle) Test(org.junit.Test)

Aggregations

Test (org.junit.Test)123 Handle (org.jdbi.v3.core.Handle)119 Jdbi (org.jdbi.v3.core.Jdbi)31 Something (org.jdbi.v3.core.Something)29 Before (org.junit.Before)20 SomethingMapper (org.jdbi.v3.core.mapper.SomethingMapper)17 SQLException (java.sql.SQLException)8 Update (org.jdbi.v3.core.statement.Update)7 GenericType (org.jdbi.v3.core.generic.GenericType)6 Query (org.jdbi.v3.core.statement.Query)6 Rule (org.junit.Rule)5 Map (java.util.Map)4 BrokenDao (org.jdbi.v3.sqlobject.subpackage.BrokenDao)4 SomethingDao (org.jdbi.v3.sqlobject.subpackage.SomethingDao)4 ImmutableMap (com.google.common.collect.ImmutableMap)3 Method (java.lang.reflect.Method)3 Connection (java.sql.Connection)3 HashMap (java.util.HashMap)3 List (java.util.List)3 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)3