2022年4月25日第四十篇

石铁生發表於2024-04-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 {

            }
        };
    }
}

相關文章