当前位置 博文首页 > 程序员石磊:oracle blob和 varchar2互相转换,mybatis 读取blob

    程序员石磊:oracle blob和 varchar2互相转换,mybatis 读取blob

    作者:[db:作者] 时间:2021-07-04 15:56

    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>
    
    cs
    下一篇:没有了