2022年4月25日第四十篇

今天构建了一个类型转换器,将图片以longblob类型存储在数据库表中。

下面使类型转换器代码

package com.example.greensage.util;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;

public class PictureToBlobTypeHander  extends BaseTypeHandler<MultipartFile> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, MultipartFile parameter, JdbcType jdbcType)
            throws SQLException {
        try {
            if (parameter != null && parameter.getBytes() != null) {
                ps.setBinaryStream(i, parameter.getInputStream());
            } else {
                ps.setNull(i, Types.LONGVARBINARY);
            }
        } catch (IOException e) {
            throw new SQLException("Error converting MultipartFile to InputStream");
        }
    }

    @Override
    public MultipartFile getNullableResult(ResultSet rs, String columnName) throws SQLException {
        InputStream inputStream = rs.getBinaryStream(columnName);
        return createMultipartFile(inputStream);
    }

    @Override
    public MultipartFile getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        InputStream inputStream = rs.getBinaryStream(columnIndex);
        return createMultipartFile(inputStream);
    }

    @Override
    public MultipartFile getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        Blob blob = cs.getBlob(columnIndex);
        InputStream inputStream = blob.getBinaryStream();
        return createMultipartFile(inputStream);
    }

    private MultipartFile createMultipartFile(InputStream inputStream) {
        return new MultipartFile() {
            @Override
            public String getName() {
                return null;
            }

            @Override
            public String getOriginalFilename() {
                return null;
            }

            @Override
            public String getContentType() {
                return null;
            }

            @Override
            public boolean isEmpty() {
                return false;
            }

            @Override
            public long getSize() {
                try {
                    return inputStream != null ? inputStream.available() : 0;
                } catch (IOException e) {
                    return 0;
                }
            }

            @Override
            public byte[] getBytes() throws IOException {
                return null;
            }

            @Override
            public InputStream getInputStream() throws IOException {
                return inputStream;
            }

            @Override
            public void transferTo(java.io.File dest) throws IOException, IllegalStateException {

            }
        };
    }
}

 

posted @ 2024-04-25 00:35  石铁生  阅读(3)  评论(0编辑  收藏  举报