All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.simpleflatmapper.jdbc.impl.CollectionIndexFieldMapper Maven / Gradle / Ivy

package org.simpleflatmapper.jdbc.impl;

import org.simpleflatmapper.converter.Context;
import org.simpleflatmapper.jdbc.MultiIndexFieldMapper;
import org.simpleflatmapper.map.setter.ContextualIndexedSetter;
import org.simpleflatmapper.reflect.Getter;
import org.simpleflatmapper.reflect.IndexedGetter;
import org.simpleflatmapper.reflect.IndexedSetter;
import org.simpleflatmapper.reflect.primitive.IntGetter;
import org.simpleflatmapper.util.ErrorHelper;

import java.sql.PreparedStatement;

public class CollectionIndexFieldMapper implements MultiIndexFieldMapper {
    private final ContextualIndexedSetter setter;
    private final Getter collectionGetter;
    private final IntGetter sizeGetter;
    private final IndexedGetter indexedGetter;

    public CollectionIndexFieldMapper(ContextualIndexedSetter setter, Getter collectionGetter, IntGetter sizeGetter, IndexedGetter indexedGetter) {
        this.setter = setter;
        this.collectionGetter = collectionGetter;
        this.sizeGetter = sizeGetter;
        this.indexedGetter = indexedGetter;
    }

    @Override
    public int map(PreparedStatement ps, T value, int columnIndex, Context context) throws Exception {
        C collection = collectionGetter.get(value);

        int size = sizeGetter.getInt(collection);

        for(int i = 0; i < size; i++) {
            setter.set(ps, indexedGetter.get(collection, i), columnIndex + i + 1, context);
        }

        return size;
    }

    @Override
    public int getSize(T value) {
        try {
            return sizeGetter.getInt(collectionGetter.get(value));
        } catch (Exception e) {
            ErrorHelper.rethrow(e);
            return 1;
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy