mybatis关于mysql存取blob数据类型

1 篇文章 0 订阅
1 篇文章 0 订阅
这篇博客详细介绍了如何在MyBatisPlus中创建并使用`CustomBlobTypeHandler`处理BLOB类型的字段,包括插入和查询数据时的转换操作。该处理器将字符串转换为字节流进行存储,并能从数据库读取回字符串。示例代码展示了在Mapper接口、Mapper配置文件以及YAML配置中的具体使用方式。
摘要由CSDN通过智能技术生成

CustomBlobTypeHandler.java

package com.jmrt.model.handler;
import org.apache.ibatis.type.*;
import org.apache.log4j.Logger;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.sql.*;

@MappedTypes(String.class)
@MappedJdbcTypes(JdbcType.BLOB)
public class CustomBlobTypeHandler extends BaseTypeHandler {

    private Logger logger = Logger.getLogger(CustomBlobTypeHandler.class);

    /**
     * []~( ̄▽ ̄)~* This method is called when data is inserted.
     * @author shy
     * @date 2022-03-29 09:50
     */
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException {
        //Declares an input stream object.
        ByteArrayInputStream bis = null;
        String param = null;
        if (parameter != null) {
            //Because we know it's a String, it depends on the situation.
            param = (String) parameter;
        }
        try {
            // Turn a string into a byte stream.
            bis = new ByteArrayInputStream(param.getBytes("utf-8"));
        } catch (Exception e) {
            logger.error("---CustomBlobTypeHandler.setNonNullParameter Exception---"+e.getMessage(),e);
            throw new RuntimeException("Blob Encoding Error!");
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    logger.error("---CustomBlobTypeHandler.setNonNullParameter IOException---"+e.getMessage(),e);
                    throw new RuntimeException("Blob Encoding Error!");
                }
            }
        }
        ps.setBinaryStream(i, bis, param.length());
    }

    /**
     * []~( ̄▽ ̄)~* This method is called when querying data.
     * @author shy
     * @date 2022-03-29 09:51
     */
    @Override
    public Object getNullableResult(ResultSet rs, String columnName) throws SQLException {
        Blob blob = (Blob) rs.getBlob(columnName);
        String result = null;
        byte[] returnValue = null;
        if (null != blob) {
            returnValue = blob.getBytes(1, (int) blob.length());

            try {
                //Converts the fetched stream object to a UTF-8 string object.
                result = new String(returnValue, "utf-8");
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("---CustomBlobTypeHandler.getNullableResult---"+e.getMessage(),e);
                throw new RuntimeException("Blob Encoding Error!");
            }

        } else {
            result = "";
        }
        return result;
    }

    @Override
    public Object getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return null;
    }

    @Override
    public Object getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return null;
    }
}

application.yml
mybatis-plus:
  mapper-locations: classpath:/mapper/*.xml
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  type-handlers-package: com.jmrt.model.handler

LockUserMapper.java
package com.jmrt.mapper;

import com.jmrt.model.LockUserModel;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 
 * 
 * @author shy
 * @email shy@mail.com
 * @date 2022-03-23 16:45:20
 */
@Mapper
@Repository
public interface LockUserMapper extends BaseMapper<LockUserModel> {

    List<LockUserModel> selectAllList(@Param("user_id") String user_id,@Param("privilege") Integer privilege, @Param("field") String field, @Param("orderType") String orderType);

    List<LockUserModel> insertUserData(@Param("useridList") List<String> useridList);
}

LockUserMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.jmrt.mapper.LockUserMapper">

	<!-- 可根据自己的需求,是否要使用 -->
    <resultMap type="com.jmrt.model.LockUserModel" id="lockUserMap">
        <result property="id" column="id" jdbcType="INTEGER"/>
        <result property="userId" column="user_id" jdbcType="VARCHAR" />
        <result property="name" column="name" jdbcType="VARCHAR"/>
        <result property="privilege" column="privilege" jdbcType="INTEGER"/>
        <result property="card" column="card" jdbcType="VARCHAR"/>
        <result property="pwd" column="pwd" jdbcType="VARCHAR"/>

        <result property="fps" column="fps" typeHandler="com.jmrt.model.handler.CustomBlobTypeHandler" />
        <result property="face" column="face" typeHandler="com.jmrt.model.handler.CustomBlobTypeHandler" />
        <result property="photo" column="photo" typeHandler="com.jmrt.model.handler.CustomBlobTypeHandler" />

        <result property="photoenroll" column="photoEnroll" jdbcType="VARCHAR"/>
        <result property="delstatus" column="delStatus" jdbcType="VARCHAR"/>
        <result property="createtime" column="createTime" jdbcType="VARCHAR"/>
        <result property="updatetime" column="updateTime" jdbcType="VARCHAR"/>
        <result property="downloadrecord" column="downloadRecord" jdbcType="VARCHAR"/>
    </resultMap>
    <select id="selectAllList" resultMap="lockUserMap">
        select * from lock_user
        <where>
            <if test="user_id!='' and user_id!=null">
                and user_id like CONCAT(CONCAT('%',#{user_id}),'%')
            </if>
            <if test="privilege!=2">
                and privilege = #{privilege}
            </if>
            and delstatus = '1'
        </where>

        order by ${field} ${orderType}
    </select>

    <select id="insertUserData" resultMap="lockUserMap">
        select * from lock_user
        where user_id in
        <foreach collection="useridList" item="userId" index="index" open="(" close=")" separator=",">
            #{userId}
        </foreach>
    </select>
</mapper>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值