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

com.kenshoo.pl.entity.internal.EntityDbUtil Maven / Gradle / Ivy

Go to download

A Java persistence layer based on JOOQ for high performance and business flow support.

There is a newer version: 0.1.121-jooq-3.16.3
Show newest version
package com.kenshoo.pl.entity.internal;

import com.kenshoo.pl.data.DatabaseId;
import com.kenshoo.pl.entity.CurrentEntityState;
import com.kenshoo.pl.entity.EntityField;
import com.kenshoo.pl.entity.EntityFieldDbAdapter;
import com.kenshoo.pl.entity.EntityType;
import com.kenshoo.pl.entity.FieldsValueMap;
import com.kenshoo.pl.entity.Identifier;
import org.jooq.Record;
import org.jooq.TableField;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.stream.Stream;


public class EntityDbUtil {

    private EntityDbUtil() {
    }

    public static > DatabaseId getDatabaseId(Identifier identifier) {
        EntityField[] fields = identifier.getUniqueKey().getFields();
        List dbValues = new ArrayList<>();
        List> tableFields = new ArrayList<>();
        for (EntityField field : fields) {
            addToArrays(identifier, field, dbValues, tableFields);
        }
        return new DatabaseId(tableFields.toArray(new TableField[tableFields.size()]), dbValues.toArray(new Object[dbValues.size()]));
    }

    private static , T> void addToArrays(Identifier identifier, EntityField field, List dbValues, List> tableFields) {
        EntityFieldDbAdapter dbAdapter = field.getDbAdapter();
        //noinspection unchecked
        dbAdapter.getTableFields().sequential().forEach(tableFields::add);
        //noinspection unchecked
        dbAdapter.getDbValues(identifier.get(field)).sequential().forEach(dbValues::add);
    }

    public static > Object[] getFieldValues(Collection> fields, FieldsValueMap fieldsValueMap) {
        return getFieldValuesInner(fields, field -> getDbValues(fieldsValueMap, field, FieldsValueMap::get));
    }

    public static > Object[] getFieldValues(Collection> fields, CurrentEntityState currentState) {
        return getFieldValuesInner(fields, field -> getDbValues(currentState, field, CurrentEntityState::get));
    }

    private static > Object[] getFieldValuesInner(Collection> fields, Function, Stream> mapper) {
        return fields.stream().flatMap(mapper).toArray();
    }

    private static , O, T> Stream getDbValues(O currentState, EntityField field, BiFunction, T> getter) {
        return field.getDbAdapter().getDbValues(getter.apply(currentState, field));
    }

}