如何使用MyBatis处理blob? [英] How to handle blob with MyBatis?

查看:977
本文介绍了如何使用MyBatis处理blob?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

java.sql.Blob 没有默认处理程序。文档建议使用 byte [] 数组,但我有一个遗留类,它使用 Blob

There is no default handler for java.sql.Blob. The documentation recommends using a byte[] array but I have a legacy class that makes use of Blob.

如何为Blob定义自定义处理程序?

How can I define a custom handler for Blob?

推荐答案

您可以覆盖 BaseTypeHandler 支持 Blob 处理如下:

You can override BaseTypeHandler to support Blob handling like this:

@MappedTypes(Blob.class)
public class CustomBlobTypeHandler extends BaseTypeHandler<Blob> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i,
            Blob parameter, JdbcType jdbcType) throws SQLException {
        InputStream is = parameter.getBinaryStream();
        try {
            ps.setBinaryStream(i, is, is.available());
        } catch (IOException e) {
            throw new SQLException(e);
        }
    }

    @Override
    public Blob getNullableResult(ResultSet rs, String columnName)
            throws SQLException {
        return rs.getBlob(columnName);
    }

    @Override
    public Blob getNullableResult(ResultSet rs, int columnIndex)
            throws SQLException {
        return rs.getBlob(columnIndex);
    }

    @Override
    public Blob getNullableResult(CallableStatement cs, int columnIndex)
            throws SQLException {
        return cs.getBlob(columnIndex);
    }

}

然后用<$注册c $ c> SqlSessionFactoryBean 使用 typeHandlersPackage 属性:

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="typeAliasesPackage" value="in.ksharma.model" />
        <property name="typeHandlersPackage" value="in.ksharma.mybatis.typehandlers" />
        <property name="mapperLocations" value="classpath*:*-mapper*.xml" />
    </bean>

这篇关于如何使用MyBatis处理blob?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆