1. 程式人生 > 實用技巧 >ORACL資料庫通過mybatis查詢BLOB或CLOB型別資料

ORACL資料庫通過mybatis查詢BLOB或CLOB型別資料

  1. 查詢BLOB型別資料

    1. 定義一個位元組陣列接收

      比如說可以定義一個接收的實體類

      @Data
      public class KnowInfoDto {
          /**
           * Id
           */
          private String id;
          
          /**
           * 內容
           */
          private String  legalContent;
      
          /**
           * 內容byte
           */
          private byte[]  legalContentByte;
      }
      
      
      1. 再到xml裡寫一個resultMap

       <resultMap id="queryBaseResultMap" type="dto.KnowInfoDto" >
          <id column="id" property="id" jdbcType="VARCHAR" />
          <result column="legalContentByte" property="legalContentByte" jdbcType="BLOB" typeHandler="org.apache.ibatis.type.BlobTypeHandler"/>
        </resultMap>
      

      需要注意的就是這個typeHandler ,要是BlobTypeHandler型別的。之後用這個byte[]z欄位去接收。

      1. 在轉化為String型別

      接收到之後需要轉換成String,可能會亂碼。所以我們需要判斷編碼型別,預設為utf-8.

      /**
           * 獲取檔案編碼型別
           *
           * @param bytes 檔案bytes陣列
           * @return      編碼型別
           */
          public static String getEncoding(byte[] bytes) {
              String defaultEncoding = "UTF-8";
              UniversalDetector detector = new UniversalDetector(null);
              detector.handleData(bytes, 0, bytes.length);
              detector.dataEnd();
              String encoding = detector.getDetectedCharset();
              detector.reset();
              if (encoding == null) {
                  encoding = defaultEncoding;
              }
              return encoding;
          }
      

      再用new String()z轉成String。

      try {
                      KnowInfoDto.setLegalContent(new String(KnowInfoDto.getLegalContentByte(),getEncoding(KnowInfoDto.getLegalContentByte())));
                  } catch (UnsupportedEncodingException e) {
                      e.printStackTrace();
                  }
      
  2. 查詢CLOB型別資料

    1. 實體類中用String接收就可以了

      @Data
      public class KnowInfoDto {
          /**
           * Id
           */
          private String id;
          
          /**
           * 內容
           */
          private String  legalContent;
      }
      
    2. xml 裡要設定一下typeHandler

      <resultMap id="queryBaseResultMap" type="dto.KnowInfoDto" >
          <id column="id" property="id" jdbcType="VARCHAR" />
          <result column="legalContent" property="legalContent" jdbcType="CLOB" typeHandler="org.apache.ibatis.type.ClobTypeHandler"/>
        </resultMap>