oracle blob和 varchar2互相转换,mybatis 读取blob乱码等相关问题总结
程序员文章站
2022-04-28 15:33:39
...
utl_raw.cast_to_raw
Oracle字符集查询
NLS_CHARACTERSET是数据库字符集,NLS_NCHAR_CHARACTERSET是国家字符集
ORACLE中有两大类字符型数据,VARCHAR2是按照数据库字符集来存储数据。而NVARCHAR2是按照国家字符集存储数据的。同样,CHAR和NCHAR也一样,一是数据库字符符,一是国家字符集。
字符集不同,二进制码的组合就不同
需求要求varchar2 加工插入blob
采用 utl_raw.cast_to_raw(‘你好啊’),
mybatis 读取byte[] 转string
package com.hcp.util;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.sql.*;
public class BlobToStringTypeHandler extends BaseTypeHandler<String> {
private static final String DEFAULT_CHARSET = "gbk";
// 这里和数据库编码一直,否则乱码、 实体保存的时候也要 getBytes("gbk")
@Override
public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
ps.setString(i, parameter);
}
@Override
public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
Blob blob = rs.getBlob(columnName);
return handle(blob);
}
@Override
public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
Blob blob = rs.getBlob(columnIndex);
return handle(blob);
}
@Override
public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
Blob blob = cs.getBlob(columnIndex);
return handle(blob);
}
private String handle( Blob blob)throws SQLException{
try {
return blob == null?null:new String(blob.getBytes(1, (int)blob.length()),DEFAULT_CHARSET);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
}
<resultMap id="ResultMapWithHcpPjyjCx" type="HcpPjyjCx">
<id column="PJYJXH" jdbcType="VARCHAR" property="pjyjxh" />
<result column="PJJGXH" jdbcType="VARCHAR" property="pjjgxh" />
<result column="PJLY_DM" jdbcType="VARCHAR" property="pjlyDm" />
<result column="PJLYMC" jdbcType="VARCHAR" property="pjlyMc" />
<result column="YJJY" jdbcType="BLOB" property="yjjy" />
<result property="yjjynr" column="YJJYNR" jdbcType="BLOB" typeHandler="com.hcp.util.BlobToStringTypeHandler"></result>
</resultMap>
上一篇: Java fail-fast 与 fail-safe 机制对比
下一篇: 做个自己站内搜索引擎