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

com.kasinf.framework.rest.eneity.converter.ObjectConverter Maven / Gradle / Ivy

There is a newer version: 1.4.0
Show newest version
package com.kasinf.framework.rest.eneity.converter;

import cn.hutool.core.util.HexUtil;
import org.hibernate.HibernateException;

import javax.persistence.AttributeConverter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class ObjectConverter implements AttributeConverter {
    @Override
    public String convertToDatabaseColumn(Object attribute) {
        if (attribute != null) {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            try (ObjectOutputStream oos = new ObjectOutputStream(bos)) {
                oos.writeObject(attribute);
                char[] chars = HexUtil.encodeHex(bos.toByteArray());
                return  String.valueOf(chars);
            } catch (Exception e) {
                throw new HibernateException(e);
            }
        }
        return null;
    }

    @Override
    public Object convertToEntityAttribute(String dbData) {
        try (ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(HexUtil.decodeHex(dbData)))) {
            return ois.readObject();
        } catch (Exception e) {
            throw new HibernateException(e);
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy