mybatis关于mysql存取blob数据类型

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>

版权声明:本文为Sayonara_LM原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。