Search in sources :

Example 1 with QualifiedType

use of org.jdbi.v3.core.qualifier.QualifiedType in project jdbi by jdbi.

the class TestNVarchar method sqlStatementBindNVarchar.

@Test
public void sqlStatementBindNVarchar() {
    h2Extension.getJdbi().useHandle(handle -> {
        handle.createUpdate("INSERT INTO nvarchars (id, name) VALUES (?, ?)").bind(0, 1).bindNVarchar(1, "foo").execute();
        handle.createUpdate("INSERT INTO nvarchars (id, name) VALUES (:id, :name)").bind("id", 2).bindNVarchar("name", "bar").execute();
        handle.createUpdate("INSERT INTO nvarchars (id, name) VALUES (?, ?)").bind(0, 3).bindByType(1, "baz", NVARCHAR_STRING).execute();
        handle.createUpdate("INSERT INTO nvarchars (id, name) VALUES (:id, :name)").bind("id", 4).bindByType("name", "qux", NVARCHAR_STRING).execute();
        assertThat(handle.select("SELECT name FROM nvarchars ORDER BY id").mapTo(QualifiedType.of(String.class).with(NVarchar.class)).list()).containsExactly("foo", "bar", "baz", "qux");
        assertThat(handle.select("SELECT name FROM nvarchars ORDER BY id").mapTo(QualifiedType.of(new GenericType<String>() {
        }).with(NVarchar.class)).list()).containsExactly("foo", "bar", "baz", "qux");
        List rawList = handle.select("SELECT name FROM nvarchars ORDER BY id").mapTo((QualifiedType<?>) NVARCHAR_STRING).list();
        assertThat(rawList).containsExactly("foo", "bar", "baz", "qux");
    });
}
Also used : GenericType(org.jdbi.v3.core.generic.GenericType) List(java.util.List) Test(org.junit.jupiter.api.Test)

Example 2 with QualifiedType

use of org.jdbi.v3.core.qualifier.QualifiedType in project jdbi by jdbi.

the class ObjectMethodArguments method load.

private static Map<String, Function<Object, TypedValue>> load(ConfigRegistry config, Class<?> type) {
    final HashMap<String, Function<Object, TypedValue>> methodMap = new HashMap<>();
    if (Modifier.isPublic(type.getModifiers())) {
        Arrays.stream(type.getMethods()).filter(m -> m.getParameterCount() == 0).collect(Collectors.toMap(Method::getName, Function.identity(), ObjectMethodArguments::bridgeMethodMerge)).forEach((name, method) -> {
            QualifiedType<?> qualifiedType = QualifiedType.of(method.getGenericReturnType()).withAnnotations(config.get(Qualifiers.class).findFor(method));
            MethodHandle mh = Unchecked.function(MethodHandles.lookup()::unreflect).apply(method);
            methodMap.put(name, Unchecked.function(value -> new TypedValue(qualifiedType, mh.invoke(value))));
        });
    } else {
        Optional.ofNullable(type.getSuperclass()).ifPresent(superclass -> methodMap.putAll(load(config, superclass)));
        Arrays.stream(type.getInterfaces()).forEach(interfaceClass -> methodMap.putAll(load(config, interfaceClass)));
    }
    return methodMap;
}
Also used : ObjectPropertyNamedArgumentFinder(org.jdbi.v3.core.argument.internal.ObjectPropertyNamedArgumentFinder) MethodHandle(java.lang.invoke.MethodHandle) Arrays(java.util.Arrays) JdbiCaches(org.jdbi.v3.core.config.JdbiCaches) MethodHandles(java.lang.invoke.MethodHandles) HashMap(java.util.HashMap) JdbiCache(org.jdbi.v3.core.config.JdbiCache) Function(java.util.function.Function) Collectors(java.util.stream.Collectors) ConfigRegistry(org.jdbi.v3.core.config.ConfigRegistry) StatementContext(org.jdbi.v3.core.statement.StatementContext) Unchecked(org.jdbi.v3.core.internal.exceptions.Unchecked) Modifier(java.lang.reflect.Modifier) Map(java.util.Map) Optional(java.util.Optional) Qualifiers(org.jdbi.v3.core.qualifier.Qualifiers) QualifiedType(org.jdbi.v3.core.qualifier.QualifiedType) Method(java.lang.reflect.Method) TypedValue(org.jdbi.v3.core.argument.internal.TypedValue) Function(java.util.function.Function) HashMap(java.util.HashMap) Method(java.lang.reflect.Method) MethodHandle(java.lang.invoke.MethodHandle) TypedValue(org.jdbi.v3.core.argument.internal.TypedValue)

Example 3 with QualifiedType

use of org.jdbi.v3.core.qualifier.QualifiedType 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();
        QualifiedType<?> elementType = magic.elementType(ctx.getConfig());
        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) UseRowReducer(org.jdbi.v3.sqlobject.statement.UseRowReducer) StatementContext(org.jdbi.v3.core.statement.StatementContext)

Example 4 with QualifiedType

use of org.jdbi.v3.core.qualifier.QualifiedType in project jdbi by jdbi.

the class JpaMapper method specialize.

@Override
@SuppressWarnings("PMD.AvoidAccessibilityAlteration")
public RowMapper<C> specialize(ResultSet rs, StatementContext ctx) throws SQLException {
    Constructor<C> constructor;
    try {
        constructor = clazz.getDeclaredConstructor();
    } catch (ReflectiveOperationException e) {
        throw new EntityMemberAccessException("Unable to get constructor for " + clazz, e);
    }
    constructor.setAccessible(true);
    List<MemberSetter<C>> setters = new ArrayList<>();
    for (int colIndex = rs.getMetaData().getColumnCount(); colIndex >= 1; colIndex--) {
        String columnLabel = rs.getMetaData().getColumnLabel(colIndex);
        JpaMember member = jpaClass.lookupMember(columnLabel);
        if (member != null) {
            QualifiedType<?> memberType = member.getQualifiedType();
            ColumnMapper<?> columnMapper = ctx.findColumnMapperFor(memberType).orElseThrow(() -> new NoSuchMapperException("No column mapper for " + memberType));
            final int columnIndex = colIndex;
            setters.add(obj -> member.write(obj, columnMapper.map(rs, columnIndex, ctx)));
        }
    }
    return (r, c) -> {
        C obj;
        try {
            obj = constructor.newInstance();
        } catch (ReflectiveOperationException e) {
            throw new EntityMemberAccessException("Unable to invoke " + constructor, e);
        }
        for (MemberSetter<C> setter : setters) {
            setter.mapAndSetMember(obj);
        }
        return obj;
    };
}
Also used : SQLException(java.sql.SQLException) List(java.util.List) ResultSet(java.sql.ResultSet) ColumnMapper(org.jdbi.v3.core.mapper.ColumnMapper) JpaMember(org.jdbi.v3.jpa.internal.JpaMember) NoSuchMapperException(org.jdbi.v3.core.mapper.NoSuchMapperException) QualifiedType(org.jdbi.v3.core.qualifier.QualifiedType) Constructor(java.lang.reflect.Constructor) ArrayList(java.util.ArrayList) RowMapper(org.jdbi.v3.core.mapper.RowMapper) StatementContext(org.jdbi.v3.core.statement.StatementContext) JpaClass(org.jdbi.v3.jpa.internal.JpaClass) ArrayList(java.util.ArrayList) NoSuchMapperException(org.jdbi.v3.core.mapper.NoSuchMapperException) JpaMember(org.jdbi.v3.jpa.internal.JpaMember)

Example 5 with QualifiedType

use of org.jdbi.v3.core.qualifier.QualifiedType in project jdbi by jdbi.

the class ResultReturner method forMethod.

/**
 * Inspect a Method for its return type, and choose a ResultReturner subclass
 * that handles any container that might wrap the results.
 * @param extensionType the type that owns the Method
 * @param method the method whose return type chooses the ResultReturner
 * @return an instance that takes a ResultIterable and constructs the return value
 */
static ResultReturner forMethod(Class<?> extensionType, Method method) {
    Type returnType = GenericTypes.resolveType(method.getGenericReturnType(), extensionType);
    QualifiedType<?> qualifiedReturnType = QualifiedType.of(returnType).withAnnotations(new Qualifiers().findFor(method));
    Class<?> returnClass = getErasedType(returnType);
    if (Void.TYPE.equals(returnClass)) {
        return findConsumer(method).orElseThrow(() -> new IllegalStateException(String.format("Method %s#%s is annotated as if it should return a value, but the method is void.", method.getDeclaringClass().getName(), method.getName())));
    } else if (ResultIterable.class.equals(returnClass)) {
        return new ResultIterableReturner(qualifiedReturnType);
    } else if (Stream.class.equals(returnClass)) {
        return new StreamReturner(qualifiedReturnType);
    } else if (ResultIterator.class.equals(returnClass)) {
        return new ResultIteratorReturner(qualifiedReturnType);
    } else if (Iterator.class.equals(returnClass)) {
        return new IteratorReturner(qualifiedReturnType);
    } else if (method.isAnnotationPresent(SingleValue.class)) {
        return new SingleValueReturner(qualifiedReturnType);
    } else {
        return new CollectedResultReturner(qualifiedReturnType);
    }
}
Also used : SingleValue(org.jdbi.v3.sqlobject.SingleValue) ResultIterator(org.jdbi.v3.core.result.ResultIterator) ResultIterable(org.jdbi.v3.core.result.ResultIterable) Type(java.lang.reflect.Type) GenericTypes.getErasedType(org.jdbi.v3.core.generic.GenericTypes.getErasedType) QualifiedType(org.jdbi.v3.core.qualifier.QualifiedType) Qualifiers(org.jdbi.v3.core.qualifier.Qualifiers)

Aggregations

QualifiedType (org.jdbi.v3.core.qualifier.QualifiedType)8 StatementContext (org.jdbi.v3.core.statement.StatementContext)7 SQLException (java.sql.SQLException)6 Map (java.util.Map)6 Test (org.junit.jupiter.api.Test)6 ResultSet (java.sql.ResultSet)5 List (java.util.List)5 Qualifiers (org.jdbi.v3.core.qualifier.Qualifiers)5 ArrayList (java.util.ArrayList)4 Optional (java.util.Optional)4 Function (java.util.function.Function)4 ConfigRegistry (org.jdbi.v3.core.config.ConfigRegistry)4 ColumnMapper (org.jdbi.v3.core.mapper.ColumnMapper)4 String.format (java.lang.String.format)3 Set (java.util.Set)3 Jdbi (org.jdbi.v3.core.Jdbi)3 RowMapper (org.jdbi.v3.core.mapper.RowMapper)3 Injector (com.google.inject.Injector)2 Key (com.google.inject.Key)2 Module (com.google.inject.Module)2