Search in sources :

Example 1 with Query

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

the class SqlStatement method bindBeanList.

/**
 * Bind a parameter for each value in the given list * number of property names,
 * and defines an attribute as the comma-separated list of parameter references (using colon prefix).
 *
 * Used to create query similar to:
 * select * from things where (id, foo) in ((1,'abc'),(2,'def'),(3,'ghi'))
 * <p>
 * Examples:
 * <pre>
 *
 * List&lt;ThingKey&gt; thingKeys = ...
 * List&lt;Thing&gt; things = handle.createQuery("select * from things where (id, foo) in (&lt;thingKeys&gt;)")
 *     .bindBeanList("thingKeys", thingKeys, Arrays.asList("id", "foo"))
 *     .mapTo(Contact.class)
 *     .list();
 * </pre>
 *
 * @param key    attribute name
 * @param values list of values that will be comma-spliced into the defined attribute value.
 * @param propertyNames list of properties that will be invoked on the values.
 * @return this
 * @throws IllegalArgumentException if the list of values or properties is empty.
 * @throws UnableToCreateStatementException If a property can't be found on an value or we can't find a Argument for it.
 */
public final This bindBeanList(String key, List<?> values, List<String> propertyNames) throws UnableToCreateStatementException {
    if (values.isEmpty()) {
        throw new IllegalArgumentException(getClass().getSimpleName() + ".bindBeanList was called with no values.");
    }
    if (propertyNames.isEmpty()) {
        throw new IllegalArgumentException(getClass().getSimpleName() + ".bindBeanList was called with no properties.");
    }
    StringBuilder names = new StringBuilder();
    StatementContext ctx = getContext();
    for (int valueIndex = 0; valueIndex < values.size(); valueIndex++) {
        if (valueIndex > 0) {
            names.append(',');
        }
        Object bean = values.get(valueIndex);
        BeanPropertyArguments beanProperties = new BeanPropertyArguments(null, bean);
        names.append("(");
        for (int propertyIndex = 0; propertyIndex < propertyNames.size(); propertyIndex++) {
            if (propertyIndex > 0) {
                names.append(",");
            }
            String propertyName = propertyNames.get(propertyIndex);
            String name = "__" + key + "_" + valueIndex + "_" + propertyName;
            names.append(':').append(name);
            Argument argument = beanProperties.find(propertyName, ctx).orElseThrow(() -> new UnableToCreateStatementException("Unable to get " + propertyName + " argument for " + bean, ctx));
            bind(name, argument);
        }
        names.append(")");
    }
    return define(key, names.toString());
}
Also used : InputStreamArgument(org.jdbi.v3.core.argument.InputStreamArgument) NullArgument(org.jdbi.v3.core.argument.NullArgument) ObjectArgument(org.jdbi.v3.core.argument.ObjectArgument) Argument(org.jdbi.v3.core.argument.Argument) CharacterStreamArgument(org.jdbi.v3.core.argument.CharacterStreamArgument) BeanPropertyArguments(org.jdbi.v3.core.argument.BeanPropertyArguments)

Example 2 with Query

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

the class SqlQueryHandler method configureReturner.

@Override
void configureReturner(Query q, SqlObjectStatementConfiguration cfg) {
    UseRowMapper useRowMapper = getMethod().getAnnotation(UseRowMapper.class);
    UseRowReducer useRowReducer = getMethod().getAnnotation(UseRowReducer.class);
    if (useRowReducer != null && useRowMapper != null) {
        throw new IllegalStateException("Cannot declare @UseRowMapper and @UseRowReducer on the same method.");
    }
    cfg.setReturner(() -> {
        StatementContext ctx = q.getContext();
        Type elementType = magic.elementType(ctx);
        if (useRowReducer != null) {
            return magic.reducedResult(q.reduceRows(rowReducerFor(useRowReducer)), ctx);
        }
        ResultIterable<?> iterable = useRowMapper == null ? q.mapTo(elementType) : q.map(rowMapperFor(useRowMapper));
        return magic.mappedResult(iterable, ctx);
    });
}
Also used : UseRowMapper(org.jdbi.v3.sqlobject.statement.UseRowMapper) Type(java.lang.reflect.Type) UseRowReducer(org.jdbi.v3.sqlobject.statement.UseRowReducer) StatementContext(org.jdbi.v3.core.statement.StatementContext)

Example 3 with Query

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

the class TestQueries method testMappedQueryObjectWithNulls.

@Test
public void testMappedQueryObjectWithNulls() throws Exception {
    h.execute("insert into something (id, name, integerValue) values (1, 'eric', null)");
    ResultIterable<Something> query = h.createQuery("select * from something order by id").mapToBean(Something.class);
    List<Something> r = query.list();
    Something eric = r.get(0);
    assertThat(eric).isEqualTo(new Something(1, "eric"));
    assertThat(eric.getIntegerValue()).isNull();
}
Also used : Something(org.jdbi.v3.core.Something) Test(org.junit.Test)

Example 4 with Query

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

the class JdbiTest method whenSelectMapToString_thenStream.

@Test
public void whenSelectMapToString_thenStream() {
    Jdbi jdbi = Jdbi.create("jdbc:hsqldb:mem:testDB", "sa", "");
    jdbi.useHandle(handle -> {
        handle.execute("create table PROJECT_5 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))");
        handle.execute("INSERT INTO PROJECT_5 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')");
        handle.execute("INSERT INTO PROJECT_5 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')");
        Query query = handle.createQuery("select name, url from PROJECT_5 order by id");
        query.mapTo(String.class).useStream((Stream<String> stream) -> assertEquals("tutorials", stream.findFirst().get()));
    });
}
Also used : Jdbi(org.jdbi.v3.core.Jdbi) Query(org.jdbi.v3.core.statement.Query) Stream(java.util.stream.Stream) Test(org.junit.Test)

Example 5 with Query

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

the class JdbiTest method whenSelectMapToMap_thenResultsAreMapEntries.

@Test
public void whenSelectMapToMap_thenResultsAreMapEntries() {
    Jdbi jdbi = Jdbi.create("jdbc:hsqldb:mem:testDB", "sa", "");
    jdbi.useHandle(handle -> {
        handle.execute("create table PROJECT_3 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))");
        handle.execute("INSERT INTO PROJECT_3 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')");
        handle.execute("INSERT INTO PROJECT_3 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')");
        Query query = handle.createQuery("select * from PROJECT_3 order by id");
        List<Map<String, Object>> list = query.mapToMap().list();
        assertEquals("tutorials", list.get(0).get("name"));
        assertEquals("REST with Spring", list.get(1).get("name"));
    });
}
Also used : Jdbi(org.jdbi.v3.core.Jdbi) Query(org.jdbi.v3.core.statement.Query) Test(org.junit.Test)

Aggregations

Test (org.junit.Test)9 Query (org.jdbi.v3.core.statement.Query)7 Jdbi (org.jdbi.v3.core.Jdbi)5 Something (org.jdbi.v3.core.Something)4 HashMap (java.util.HashMap)2 Handle (org.jdbi.v3.core.Handle)2 Update (org.jdbi.v3.core.statement.Update)2 ImmutableList (com.google.common.collect.ImmutableList)1 ImmutableMap (com.google.common.collect.ImmutableMap)1 Type (java.lang.reflect.Type)1 SQLException (java.sql.SQLException)1 ArrayList (java.util.ArrayList)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 Set (java.util.Set)1 TreeSet (java.util.TreeSet)1 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)1