分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 技术分享

Mybatis Blob和String互转,实现文件上传等。

发布时间:2023-09-06 02:23责任编辑:郭大石关键词:文件上传

这样的代码网上有很多,但是本人亲测有bug,

下面是我写的代码。望参考

 1 @MappedJdbcTypes(JdbcType.BLOB) 2 public class BlobAndStringTypeHandler extends BaseTypeHandler<String> { 3 ?4 ????private static final String DEFAULT_CHARSET = "UTF-8"; //感觉没屌用 5 ?6 ????@Override 7 ????public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException { 8 ????????ByteArrayInputStream bis = null; 9 ????????bis = new ByteArrayInputStream(parameter.getBytes());10 ????????ps.setBinaryStream(i, bis, parameter.getBytes().length); //网上都是直接paramter.length() 这样是不对的。 11 12 ????}13 14 ????@Override15 ????public String getNullableResult(ResultSet rs, String columnName) throws SQLException {16 ????????Blob blob = rs.getBlob(columnName);17 ????????byte[] returnValue = null;18 ????????String result = null;19 ????????if (null != blob) {20 ????????????returnValue = blob.getBytes(1, (int) blob.length());21 ????????}22 ????????//将取出的流对象转为utf-8的字符串对象23 ????????if (null != returnValue) {24 ????????????result = new String(returnValue);25 ????????}26 ????????return result;27 ????}28 29 ????@Override30 ????public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {31 ????????Blob blob = rs.getBlob(columnIndex);32 ????????byte[] returnValue = null;33 ????????String result = null;34 ????????if (null != blob) {35 ????????????returnValue = blob.getBytes(1, (int) blob.length());36 ????????}37 ????????//将取出的流对象转为utf-8的字符串对象38 ????????if (null != returnValue) {39 ????????????result = new String(returnValue);40 ????????}41 ????????return result;42 ????}43 44 ????@Override45 ????public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {46 ????????Blob blob = cs.getBlob(columnIndex);47 ????????byte[] returnValue = null;48 ????????String result = null;49 ????????if (null != blob) {50 ????????????returnValue = blob.getBytes(1, (int) blob.length());51 ????????}52 ????????//将取出的流对象转为utf-8的字符串对象53 ????????if (null != returnValue) {54 ????????????result = new String(returnValue);55 ????????}56 ????????return result;57 ????}58 }

下面简单介绍下 String.length()和String.getBytes().length()的区别:

String.length();字符串的长度,一个中文一个长度,就是一个字符

String.getBytes().length(): 字符串包含字节的长度,一个中文两个长度,就是两个字节

Mybatis Blob和String互转,实现文件上传等。

原文地址:https://www.cnblogs.com/haoerlv/p/9982244.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved