Mybatis自定义typeHandlers

早过忘川 提交于 2020-01-10 01:52:30

类型处理器(typeHandlers):

MyBatis 在预处理语句(PreparedStatement)中设置一个参数时,还是从结果集中取出一个值时, 都会用类型处理器将获取的值以合适的方式转换成 Java 类型。Mybatis有默认的类型处理器,但是如果我们重新配置了,将会覆盖对应的类型处理器
具体实现如下:
1.创建处理器类,实现 org.apache.ibatis.type.TypeHandler 接口,或者继承 org.apache.ibatis.type.BaseTypeHandler, 然后可以选择性地将它映射到一个 JDBC 类型。
package com.jym.util;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.sql.*;
// MappedJdbcTypes注解,设置处理的数据库类型
@MappedJdbcTypes(JdbcType.BLOB)
// 设置转换的类型,意思是将数据库的BLOB类型与JAVA的byte[]类型实现相互转换
public class BlobUtil extends BaseTypeHandler<byte[]> {


    // 设置传参转换,将byte[]转换为Blob,i为参数索引
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, byte[] bytes, JdbcType jdbcType) throws SQLException {
        InputStream input = new ByteArrayInputStream(bytes);
        preparedStatement.setBlob(i,input);
    }

    // 将查询的结果集里的Blob类型转换为byte[]
    public byte[] getNullableResult(ResultSet resultSet, String s) throws SQLException {
        Blob blob = resultSet.getBlob(s);
        Long length = blob.length();
        byte[] bytes = blob.getBytes(1, length.intValue());
        return bytes;
    }

    // 将查询的结果集里的Blob类型转换为byte[]
    public byte[] getNullableResult(ResultSet resultSet, int i) throws SQLException {
        Blob blob = resultSet.getBlob(i);
        Long length = blob.length();
        byte[] bytes = blob.getBytes(1, length.intValue());
        return bytes;
    }

    // 将查询的结果集里的Blob类型转换为byte[]
    public byte[] getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        Blob blob = callableStatement.getBlob(i);
        Long length = blob.length();
        byte[] bytes = blob.getBytes(1, length.intValue());
        return bytes;
    }
}

2.在xml文件中配置
    <typeHandlers>
        <typeHandler handler="com.jym.util.BlobUtil"/>
    </typeHandlers>
mapper.xml:
    <!-- 批量增加,若使用自增主键,则设置useGeneratedKeys="true",keyProperty="id"  -->
    <insert id="insertUser" >
          insert into USER (id,email,hope_job,name,personal_evaluation,personal_skills,phone_number,user_image) values
          <foreach collection="list"  item="user" separator=",">
              (#{user.id},#{user.email},#{user.hopeJob},#{user.name},#{user.personalEvaluation},#{user.personalSkills},#{user.phoneNumber},#{user.userImage})
          </foreach>
    </insert>

    <!-- 当resultType为List,HashMap的时候,不需要写全类名,其他的需要全类名,否则报错,除非配置类型别名
         mybatis会创建一个预处理语句(PreparedStatement)参数,等同于如下代码:
         String sql = " select * from USER where id =?";
         PreparedStatement ps = conn.prepareStatement(sql);
         ps.setString(1,id);   -->
    <select id="selectMapById" parameterType="String" resultType="java.util.LinkedHashMap">
        select * from USER where id = #{id}
    </select>
测试代码(添加与查找):
    @Test
    public void insertBlobTest() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();
//        会开启一个事务(也就是不自动提交)。
//        将从由当前环境配置的 DataSource 实例中获取 Connection 对象。
//        事务隔离级别将会使用驱动或数据源的默认设置。
//        预处理语句不会被复用,也不会批量处理更新。
        UserDao mapper = session.getMapper(UserDao.class);
        User user ;
        List<User> userList = new ArrayList<User>();
        user = new User();
        user.setEmail("751566027@qq.com");
        user.setHopeJob("java");
        user.setId(String.valueOf(System.currentTimeMillis()));
        user.setName("QWQ");
        user.setPersonalEvaluation("spring");
        user.setPersonalSkills("spring");
        user.setPhoneNumber("38438");
        byte[] bytes = {1,1,1,1,1,1,};
        user.setUserImage(bytes);
        userList.add(user);
        mapper.insertUser(userList);
        // 提交事务
        session.commit();
        session.close();
    }

    @Test
    public void sqlTest() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//      会开启一个事务(也就是不自动提交)。
//      将从由当前环境配置的 DataSource 实例中获取 Connection 对象。
//      事务隔离级别将会使用驱动或数据源的默认设置。
//      预处理语句不会被复用,也不会批量处理更新。
        SqlSession session = sqlSessionFactory.openSession();
//        LinkedHashMap<String, Object> stringObjectLinkedHashMap
//                = (LinkedHashMap<String, Object>)session.selectOne("com.jym.dao.UserDao.selectMapById","0");
        UserDao mapper = session.getMapper(UserDao.class);
        LinkedHashMap<String, Object> stringObjectLinkedHashMap = mapper.selectMapById("1578568140608");
        byte[] bytes = (byte[])stringObjectLinkedHashMap.get("user_image");
        System.out.println(bytes.length);
    }

在这里插入图片描述

世界上有10种人,一种是懂二进制的,一种是不懂二进制的。

感谢您的收看,如有哪里写的不对 请留言,谢谢。

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