定義實體類
映射實體字段類型為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
類型數據操作即可,數據處理轉換在自定義類中已經完成了。
參考了很多其他文章,因為這是我半夜在宿舍寫的,沒有記錄下來引用、參考文章出處,在此非常抱歉!
有不足之處歡迎指正!