Mybatis Oracle 存取BLOB类型数据

<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">和大家分享下如何处理BLOB存取,此类来源于Mybatis官方文档,网上有许多方法,但是都感觉用起来很不顺手,解决方法不如官方文档明白清楚。</span>

先建一个实体类BlobRecord.java

package org.apache.ibatis.submitted.blobtest;

public class BlobRecord {
    private int id;
    private byte[] blob;

    public BlobRecord(int id, byte[] blob) {
        super();
        this.id = id;
        this.blob = blob;
    }

    public BlobRecord(int id, Byte[] blob) {
        super();
        this.id = id;
        final byte[] newBytes = new byte[blob.length];
        for (int i = 0; i < blob.length; i++) {
          Byte b = blob[i];
          newBytes[i] = b;
        }
        this.blob = newBytes;
    }

    public int getId() {
        return id;
    }

    public byte[] getBlob() {
        return blob;
    }
}

然后是SQL的XML

<mapper namespace="org.apache.ibatis.submitted.blobtest.BlobMapper">
  <resultMap type="org.apache.ibatis.submitted.blobtest.BlobRecord" id="blobRecordResult">
    <constructor>
      <idArg column="id" javaType="_int"/>
      <arg column="blob" javaType="_byte[]"/>
    </constructor>
  </resultMap>

  <resultMap type="org.apache.ibatis.submitted.blobtest.BlobRecord" id="blobRecordResultWithBlobObjects">
    <constructor>
      <idArg column="id" javaType="_int"/>
      <arg column="blob" javaType="Byte[]"/>
    </constructor>
  </resultMap>
  
  <insert id="insert" parameterType="org.apache.ibatis.submitted.blobtest.BlobRecord">
    insert into blobtest.blobs values (#{id}, #{blob})
  </insert>
  
  <select id="selectAll" resultMap="blobRecordResult">
    select * from blobtest.blobs
  </select>

  <select id="selectAllWithBlobObjects" resultMap="blobRecordResultWithBlobObjects">
    select * from blobtest.blobs
  </select>
</mapper>


最后是调用的Java代码

BlobMapper.java


package org.apache.ibatis.submitted.blobtest;

import java.util.List;

public interface BlobMapper {
    int insert(BlobRecord blobRecord);
    List<BlobRecord> selectAll();
    List<BlobRecord> selectAllWithBlobObjects();
}



猜你喜欢

转载自blog.csdn.net/lvsehuoyan/article/details/42016061