MyBatis读取MySql中BLOB数据

本文介绍了一种自定义MyBlobTypeHandler的方法,用于在Java应用程序中实现Blob和String之间的相互转换,适用于MyBatis框架。该Handler可以方便地处理数据库中Blob字段的读写操作。

首先自定义一个handler用来处理blob和string之间的转换

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. import java.io.ByteArrayInputStream;  
  2. import java.io.UnsupportedEncodingException;  
  3. import java.sql.Blob;  
  4. import java.sql.CallableStatement;  
  5. import java.sql.PreparedStatement;  
  6. import java.sql.ResultSet;  
  7. import java.sql.SQLException;  
  8.   
  9. import org.apache.commons.logging.Log;  
  10. import org.apache.commons.logging.LogFactory;  
  11. import org.apache.ibatis.type.BaseTypeHandler;  
  12. import org.apache.ibatis.type.JdbcType;  
  13.   
  14. /** 
  15.  * 项目名称: 
  16.  *  
  17.  * @description: 
  18.  *  
  19.  * @author spg 
  20.  *  
  21.  * @create_time:2014年7月24日 下午8:49:02 
  22.  *  
  23.  * @version V1.0.0 
  24.  *  
  25.  */  
  26. public class MyBlobTypeHandler extends BaseTypeHandler<String>  
  27. {  
  28.   
  29.     private static final Log LOGGER = LogFactory  
  30.             .getLog(MyBlobTypeHandler.class);  
  31.     // 指定字符集  
  32.     private static final String DEFAULT_CHARSET = "utf-8";  
  33.   
  34.     @Override  
  35.     public void setNonNullParameter(PreparedStatement ps, int i,  
  36.             String parameter, JdbcType jdbcType) throws SQLException  
  37.     {  
  38.         ByteArrayInputStream bis;  
  39.         try  
  40.         {  
  41.             // 把String转化成byte流  
  42.             bis = new ByteArrayInputStream(parameter.getBytes(DEFAULT_CHARSET));  
  43.         } catch (UnsupportedEncodingException e)  
  44.         {  
  45.             throw new RuntimeException("Blob Encoding Error!");  
  46.         }  
  47.         ps.setBinaryStream(i, bis, parameter.length());  
  48.     }  
  49.   
  50.     @Override  
  51.     public String getNullableResult(ResultSet rs, String columnName)  
  52.             throws SQLException  
  53.     {  
  54.         Blob blob = rs.getBlob(columnName);  
  55.         byte[] returnValue = null;  
  56.         String result = null;  
  57.         if (null != blob)  
  58.         {  
  59.             returnValue = blob.getBytes(1, (int) blob.length());  
  60.         }  
  61.         try  
  62.         {  
  63.             if (null != returnValue)  
  64.             {  
  65.                 // 把byte转化成string  
  66.                 result = new String(returnValue, DEFAULT_CHARSET);  
  67.             }  
  68.         } catch (UnsupportedEncodingException e)  
  69.         {  
  70.             throw new RuntimeException("Blob Encoding Error!");  
  71.         }  
  72.         return result;  
  73.     }  
  74.   
  75.     @Override  
  76.     public String getNullableResult(CallableStatement cs, int columnIndex)  
  77.             throws SQLException  
  78.     {  
  79.         Blob blob = cs.getBlob(columnIndex);  
  80.         byte[] returnValue = null;  
  81.         String result = null;  
  82.         if (null != blob)  
  83.         {  
  84.             returnValue = blob.getBytes(1, (int) blob.length());  
  85.         }  
  86.         try  
  87.         {  
  88.             if (null != returnValue)  
  89.             {  
  90.                 result = new String(returnValue, DEFAULT_CHARSET);  
  91.             }  
  92.         } catch (UnsupportedEncodingException e)  
  93.         {  
  94.             throw new RuntimeException("Blob Encoding Error!");  
  95.         }  
  96.         return result;  
  97.     }  
  98.   
  99.     /** 
  100.      * @Description: 
  101.      *  
  102.      * @param arg0 
  103.      * @param arg1 
  104.      * @return 
  105.      * @throws SQLException 
  106.      *  
  107.      * @see org.apache.ibatis.type.BaseTypeHandler#getNullableResult(java.sql.ResultSet, 
  108.      *      int) 
  109.      *  
  110.      */  
  111.   
  112.     @Override  
  113.     public String getNullableResult(ResultSet rs, int columnName)  
  114.             throws SQLException  
  115.     {  
  116.         LOGGER.debug("enter function");  
  117.         String result = null;  
  118.         Blob blob = rs.getBlob(columnName);  
  119.         byte[] returnValue = null;  
  120.         if (null != blob)  
  121.         {  
  122.             returnValue = blob.getBytes(1, (int) blob.length());  
  123.         }  
  124.         try  
  125.         {  
  126.             // 把byte转化成string  
  127.             if (null != returnValue)  
  128.             {  
  129.                 result = new String(returnValue, DEFAULT_CHARSET);  
  130.             }  
  131.         } catch (UnsupportedEncodingException e)  
  132.         {  
  133.             throw new RuntimeException("Blob Encoding Error!");  
  134.         }  
  135.         LOGGER.debug("exit function");  
  136.         return result;  
  137.   
  138.     }  
  139. }  
resultMap中添加handler配置,如下:

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <result property="filed11" column="filed11"  typeHandler="com.eebbk.cms.common.MyBlobTypeHandler" />  

OK!这样查出来的结果就是string类型

同理,如果对与枚举类型也可通过此方式进行转换!

MyBatis 是一个流行的 Java 框架,用于简化 ORM (Object-Relational Mapping) 工作,它处理 SQL 查询并在 Java 对象和数据库之间建立映射。对于 MySQL 中的大二进制数据Blob),MyBatis 提供了支持。 当你需要存储大容量的数据,如图片、视频等 binary 数据时,MySQL Blob 类型就派上用场了。MyBatis 通过以下步骤操作 Blob: 1. **配置映射文件**:在 MyBatis 的 XML 映射文件(`mybatis-config.xml` 或 `mapper.xml`)中,为 Blob 字段设置 `<result>` 标签,并指定结果类型的 `typeHandler`,例如 `org.apache.ibatis.type.BlobTypeHandler`。例如: ```xml <select id="selectBlob" resultType="com.example.YourModel"> SELECT blob_column FROM your_table WHERE some_condition; <result column="blob_column" jdbcType="BLOB" property="yourBlobField" typeHandler="com.example.YourTypeHandler"/> </select> ``` 2. **创建类型处理器(Type Handler)**:自定义一个实现了 `org.apache.ibatis.type.TypeHandler` 接口的类,以便将 Blob 字符串转换成 Java 对象或反向。例如,你可以实现 `readBlob` 和 `writeBlob` 方法来处理读取和写入 Blob 数据数据库和从数据库获取。 ```java public class YourTypeHandler implements TypeHandler<Blob> { // 实现 readBlob 和 writeBlob 方法... } ``` 3. **读取 Blob**:在 Java 代码中,使用 MyBatis 的 DAO 或 Mapper 接口执行查询并获取 Blob 对象,通常会先转化为字节数组(byte[]): ```java YourModel model = sqlSession.selectOne("selectBlob", someParameter); byte[] blobData = model.getYourBlobField(); ``` 4. **写入 Blob**:当需要更新或插入 Blob 时,同样可以先转换为字节数组,然后通过 MyBatis 插入或更新方法传递: ```java YourModel updatedModel = new YourModel(...); updatedModel.setYourBlobField(blobData); int rowsAffected = sqlSession.update("updateYourTable", updatedModel); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值