Search in sources :

Example 1 with Bind

use of org.jdbi.v3.sqlobject.customizer.Bind 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 Bind

use of org.jdbi.v3.sqlobject.customizer.Bind in project jdbi by jdbi.

the class TestArgumentFactory method testOnPreparedBatch.

@Test
public void testOnPreparedBatch() throws Exception {
    Handle h = dbRule.getSharedHandle();
    PreparedBatch batch = h.prepareBatch("insert into something (id, name) values (:id, :name)");
    batch.registerArgument(new NameAF());
    batch.bind("id", 1).bind("name", new Name("Brian", "McCallister")).add();
    batch.bind("id", 2).bind("name", new Name("Henning", "S")).add();
    batch.execute();
    List<String> rs = h.createQuery("select name from something order by id").mapTo(String.class).list();
    assertThat(rs.get(0)).isEqualTo("Brian McCallister");
    assertThat(rs.get(1)).isEqualTo("Henning S");
}
Also used : PreparedBatch(org.jdbi.v3.core.statement.PreparedBatch) Handle(org.jdbi.v3.core.Handle) Test(org.junit.Test)

Example 3 with Bind

use of org.jdbi.v3.sqlobject.customizer.Bind in project jdbi by jdbi.

the class TestVavrValueArgumentFactoryWithDB method testGetValidationValid_shouldReturnCorrectRow.

@Test
public void testGetValidationValid_shouldReturnCorrectRow() {
    Something result = dbRule.getSharedHandle().createQuery(SELECT_BY_NAME).bind("name", Validation.valid("brian")).mapToBean(Something.class).findOnly();
    assertThat(result).isEqualTo(BRIAN_SOMETHING);
}
Also used : Something(org.jdbi.v3.core.Something) Test(org.junit.Test)

Example 4 with Bind

use of org.jdbi.v3.sqlobject.customizer.Bind in project jdbi by jdbi.

the class TestDocumentation method testFiveMinuteFluentApi.

@Test
public void testFiveMinuteFluentApi() throws Exception {
    try (Handle h = dbRule.openHandle()) {
        h.execute("insert into something (id, name) values (?, ?)", 1, "Brian");
        String name = h.createQuery("select name from something where id = :id").bind("id", 1).mapTo(String.class).findOnly();
        assertThat(name).isEqualTo("Brian");
    }
}
Also used : Handle(org.jdbi.v3.core.Handle) Test(org.junit.Test)

Example 5 with Bind

use of org.jdbi.v3.sqlobject.customizer.Bind in project jdbi by jdbi.

the class BindJpaFactory method createForParameter.

@Override
public SqlStatementParameterCustomizer createForParameter(Annotation annotation, Class<?> sqlObjectType, Method method, Parameter param, int index, Type type) {
    BindJpa bind = (BindJpa) annotation;
    final String prefix;
    if (bind.value().isEmpty()) {
        prefix = "";
    } else {
        prefix = bind.value() + ".";
    }
    return (stmt, arg) -> {
        JpaClass<?> jpaClass = JpaClass.get(arg.getClass());
        for (JpaMember member : jpaClass.members()) {
            stmt.bindByType(prefix + member.getColumnName(), readMember(arg, member), member.getType());
        }
    };
}
Also used : EntityMemberAccessException(org.jdbi.v3.jpa.EntityMemberAccessException) BindJpa(org.jdbi.v3.jpa.BindJpa) Type(java.lang.reflect.Type) Parameter(java.lang.reflect.Parameter) SqlStatementCustomizerFactory(org.jdbi.v3.sqlobject.customizer.SqlStatementCustomizerFactory) Annotation(java.lang.annotation.Annotation) SqlStatementParameterCustomizer(org.jdbi.v3.sqlobject.customizer.SqlStatementParameterCustomizer) Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException) BindJpa(org.jdbi.v3.jpa.BindJpa)

Aggregations

Test (org.junit.Test)34 Handle (org.jdbi.v3.core.Handle)18 Something (org.jdbi.v3.core.Something)15 Jdbi (org.jdbi.v3.core.Jdbi)4 Annotation (java.lang.annotation.Annotation)2 Method (java.lang.reflect.Method)2 Parameter (java.lang.reflect.Parameter)2 Type (java.lang.reflect.Type)2 OptionalFields (net.morimekta.test.providence.storage.jdbc.OptionalFields)2 PreparedBatch (org.jdbi.v3.core.statement.PreparedBatch)2 Query (org.jdbi.v3.core.statement.Query)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 Types (java.sql.Types)1 Clock (java.time.Clock)1 HashMap (java.util.HashMap)1 Optional (java.util.Optional)1 ProvidenceJdbi.columnsFromAllFields (net.morimekta.providence.jdbi.v3.ProvidenceJdbi.columnsFromAllFields)1 ProvidenceJdbi.forMessage (net.morimekta.providence.jdbi.v3.ProvidenceJdbi.forMessage)1 ProvidenceJdbi.toField (net.morimekta.providence.jdbi.v3.ProvidenceJdbi.toField)1 ProvidenceJdbi.toMessage (net.morimekta.providence.jdbi.v3.ProvidenceJdbi.toMessage)1