定义实体类
映射实体字段类型为String
@TableField("DATASTR")
private String datastr;
创建数据类型映射转换类
package com.zz.spxt.mapper;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.sql.*;
/**
* @Author: yang
* @Date: Create in 2020/6/18
* @Description:
* @Modify By:
*/
public class BlobTypeHandle extends BaseTypeHandler<String> {
private static final String DEFAULT_CHARSET = "UTF-8";
@Override
public void setNonNullParameter( PreparedStatement preparedStatement, int i, String s, JdbcType jdbcType ) throws SQLException
{
ByteArrayInputStream bis;
try
{
/* 把String转化成byte流 */
bis = new ByteArrayInputStream( s.getBytes( DEFAULT_CHARSET ) );
} catch ( UnsupportedEncodingException e )
{
throw new RuntimeException( "Blob Encoding Error!" );
}
preparedStatement.setBinaryStream( i, bis, s.length() );
}
@Override
public String getNullableResult( ResultSet resultSet, String s ) throws SQLException
{
Blob blob = resultSet.getBlob( s );
byte[] returnValue = null;
String result = null;
if ( null != blob )
{
returnValue = blob.getBytes( 1, (int) blob.length() );
}
try
{
if ( null != returnValue )
{
/* 把byte转化成string */
result = new String( returnValue, DEFAULT_CHARSET );
}
} catch ( UnsupportedEncodingException e )
{
throw new RuntimeException( "Blob Encoding Error!" );
}
return(result);
}
@Override
public String getNullableResult( ResultSet resultSet, int i ) throws SQLException
{
Blob blob = resultSet.getBlob( i );
byte[] returnValue = null;
String result = null;
if ( null != blob )
{
returnValue = blob.getBytes( 1, (int) blob.length() );
}
try
{
if ( null != returnValue )
{
result = new String( returnValue, DEFAULT_CHARSET );
}
} catch ( UnsupportedEncodingException e )
{
throw new RuntimeException( "Blob Encoding Error!" );
}
return(result);
}
@Override
public String getNullableResult( CallableStatement callableStatement, int i ) throws SQLException
{
String result = null;
Blob blob = callableStatement.getBlob( i );
byte[] returnValue = null;
if ( null != blob )
{
returnValue = blob.getBytes( 1, (int) blob.length() );
}
try
{
/* 把byte转化成string */
if ( null != returnValue )
{
result = new String( returnValue, DEFAULT_CHARSET );
}
} catch ( UnsupportedEncodingException e )
{
throw new RuntimeException( "Blob Encoding Error!" );
}
return(result);
}
}
在mapper.xml
映射中指定转换类
<result column="UPDATE_DATE" property="updateDate" />
<result column="UPDATE_UID" property="updateUid" />
<result column="DATASTR" property="datastr" typeHandler="com.zz.spxt.mapper.BlobTypeHandle"/>
使用
在使用过程中按照String
类型数据操作即可,数据处理转换在自定义类中已经完成了。
参考了很多其他文章,因为这是我半夜在宿舍写的,没有记录下来引用、参考文章出处,在此非常抱歉!
有不足之处欢迎指正!