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

com.itcoon.common.jpa.converter.AbstractCollectionToStringConverter Maven / Gradle / Ivy

There is a newer version: 1.1.2.RELEASE
Show newest version
package com.itcoon.common.jpa.converter;

import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.persistence.AttributeConverter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.function.Supplier;
import java.util.stream.Collectors;

public abstract class AbstractCollectionToStringConverter> implements AttributeConverter, String>, CollectionSupplier {


    @Override
    public String convertToDatabaseColumn(Collection attributes) {
        if (!CollectionUtils.isEmpty(attributes)) {
            StringBuilder sb = new StringBuilder();
            for (T attribute : attributes) {
                sb.append(";").append(attributeToColumnString(attribute));
            }
            return sb.toString().replaceFirst(";", "");
        }
        return null;
    }

    @Override
    public Collection convertToEntityAttribute(String columnVal) {
        Collection attributes = new ArrayList<>();
        if (!StringUtils.isEmpty(columnVal)) {
            String[] datas = columnVal.split(";");
            attributes = Arrays.stream(datas).map(this::columnSplitToAttribute).collect(Collectors.toCollection(this::supplyCollection));
        }
        return attributes;
    }

    protected abstract T columnSplitToAttribute(String columnSplit);

    protected abstract String attributeToColumnString(T attribute);

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy