Fetching a LONGBLOB as a byte array using MyBatis

给你一囗甜甜゛ 提交于 2019-12-19 04:04:54

问题


I am using MyBatis in a project, where I have a query that gets data from a LONGBLOB field in a MySQL database. I wish to get the result as a byte array (byte[]), so I try this:

<select id="fetchData" resultType="_byte[]" parameterType="_long">
    select blobData from Table where id = #{id}
</select>

This does not work, however. I get the following error:

java.lang.ClassCastException: [B cannot be cast to [Ljava.lang.Object;
    at org.apache.ibatis.binding.MapperMethod.convertToArray(MapperMethod.java:146)
    at org.apache.ibatis.binding.MapperMethod.executeForMany(MapperMethod.java:129)
    at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:90)
    at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:40)

Something tells me I should specify a type handler (BlobTypeHandler?), or something? But where and how?


I should mention that I have no problem getting around this problem by creating a wrapper class for the byte array and using a result map:

<resultMap type="BlobData" id="BlobDataMap">
    <constructor>
        <idArg javaType="_long" column="id" />
        <arg javaType="_byte[]" column="blobData" />
    </constructor>
</resultMap>

Still I am wondering if there's a more elegant way that does not involve creating a wrapper class.


回答1:


in my project we use blobs this way:

we define a result map for our used class:

<resultMap class="SomeClass" id="SomeClassResultMap">
    <result property="classByteAttribute" column="blobData" />
    <result property="classIdAttribute" column="id" />
</resultMap>

and in the select statement we use this result map

<select id="selectStatement" resultMap="SomeClassResultMap" parameterClass="Integer">
    SELECT * FROM EXAMPLETABLE where id=#id#
</select>

after the execution the blob is in the byte array.




回答2:


As suggested by duffy the only way to get the result as a byte array is:

Mybatis Version 3.1.+

define a resultMap

<resultMap class="MyClass" id="MyClassMap">
    <result property="myByteArray" column="MYBINARY " />
</resultMap>

<select id="selectStatement"  resultMap="MyClassMap">
        SELECT MYBINARY FROM EXAMPLETABLE
</select>

but,

Mybatis Version 3.0.5

<select id="selectStatement"  resultType="_byte[]">
    SELECT MYBINARY FROM EXAMPLETABLE
</select>

it is a strange regression since mybatis is not able to apply the correct (BlobTypeHandler) TypeHandler, and is not possible to specify the TypeHandler on select tag.



来源:https://stackoverflow.com/questions/14232703/fetching-a-longblob-as-a-byte-array-using-mybatis

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!