Search in sources :

Example 16 with Update

use of org.jdbi.v3.core.statement.Update 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)

Example 17 with Update

use of org.jdbi.v3.core.statement.Update in project jdbi by jdbi.

the class TestTimingCollector method testUpdate.

@Test
public void testUpdate() throws Exception {
    String stmt1 = "insert into something (id, name) values (1, 'eric')";
    String stmt2 = "update something set name = :name where id = :id";
    String stmt3 = "select * from something where id = :id";
    h.execute(stmt1);
    h.createUpdate(stmt2).bind("id", 1).bind("name", "ERIC").execute();
    Something eric = h.createQuery(stmt3).bind("id", 1).mapToBean(Something.class).list().get(0);
    assertThat(eric.getName()).isEqualTo("ERIC");
    assertThat(tc.getRawStatements()).containsExactly(stmt1, stmt2, stmt3);
    assertThat(tc.getRenderedStatements()).containsExactly(stmt1, stmt2, stmt3);
    assertThat(tc.getParsedStatements()).extracting("sql").containsExactly(stmt1, "update something set name = ? where id = ?", "select * from something where id = ?");
}
Also used : Something(org.jdbi.v3.core.Something) Test(org.junit.Test)

Example 18 with Update

use of org.jdbi.v3.core.statement.Update in project jdbi by jdbi.

the class TestUpdateGeneratedKeys method testInsert.

@Test
public void testInsert() throws Exception {
    Handle h = dbRule.openHandle();
    Update insert1 = h.createUpdate("insert into something_else (name) values (:name)");
    insert1.bind("name", "Brian");
    Long id1 = insert1.executeAndReturnGeneratedKeys().mapTo(long.class).findOnly();
    assertThat(id1).isNotNull();
    Update insert2 = h.createUpdate("insert into something_else (name) values (:name)");
    insert2.bind("name", "Tom");
    Long id2 = insert2.executeAndReturnGeneratedKeys().mapTo(long.class).findOnly();
    assertThat(id2).isNotNull();
    assertThat(id2).isGreaterThan(id1);
}
Also used : Handle(org.jdbi.v3.core.Handle) Test(org.junit.Test)

Example 19 with Update

use of org.jdbi.v3.core.statement.Update in project jdbi by jdbi.

the class TestMixinInterfaces method testJustJdbiTransactions.

@Test
public void testJustJdbiTransactions() throws Exception {
    try (Handle h1 = db.open();
        Handle h2 = db.open()) {
        h1.execute("insert into something (id, name) values (8, 'Mike')");
        h1.begin();
        h1.execute("update something set name = 'Miker' where id = 8");
        assertThat(h2.createQuery("select name from something where id = 8").mapTo(String.class).findOnly()).isEqualTo("Mike");
        h1.commit();
    }
}
Also used : Handle(org.jdbi.v3.core.Handle) Test(org.junit.Test)

Example 20 with Update

use of org.jdbi.v3.core.statement.Update in project jdbi by jdbi.

the class TestDocumentation method testUpdateAPI.

@Test
public void testUpdateAPI() throws Exception {
    try (Handle h = dbRule.openHandle()) {
        Update u = h.attach(Update.class);
        u.insert(17, "David");
        u.update(new Something(17, "David P."));
        String name = h.createQuery("select name from something where id = 17").mapTo(String.class).findOnly();
        assertThat(name).isEqualTo("David P.");
    }
}
Also used : SqlUpdate(org.jdbi.v3.sqlobject.statement.SqlUpdate) Something(org.jdbi.v3.core.Something) Handle(org.jdbi.v3.core.Handle) Test(org.junit.Test)

Aggregations

Test (org.junit.Test)19 Handle (org.jdbi.v3.core.Handle)10 Update (org.jdbi.v3.core.statement.Update)8 Something (org.jdbi.v3.core.Something)6 Jdbi (org.jdbi.v3.core.Jdbi)4 ExtensionMethod (org.jdbi.v3.core.extension.ExtensionMethod)4 HashMap (java.util.HashMap)3 SqlUpdate (org.jdbi.v3.sqlobject.statement.SqlUpdate)2 ImmutableList (com.google.common.collect.ImmutableList)1 ImmutableMap (com.google.common.collect.ImmutableMap)1 ArrayList (java.util.ArrayList)1 Arrays (java.util.Arrays)1 Collection (java.util.Collection)1 Collections (java.util.Collections)1 LinkedHashMap (java.util.LinkedHashMap)1 List (java.util.List)1 Map (java.util.Map)1 Optional (java.util.Optional)1 Set (java.util.Set)1 TreeSet (java.util.TreeSet)1