MyBatis BlobTypeHandler reads Blob fields

MyBatis also supports the Blob field of the database. It provides a BlobTypeHandler. In order to cope with more scenarios, it also provides ByteArrayTypeHandler, but it is not commonly used. Here we will show readers how to use BlobTypeHandler. First create a table.

create table file(
    id int(12) not null auto_increment,
    content blob not null,
    primary key(id)
);

Bold code, using the Blob field, is used to save the file. Then create a POJO for handling this table as shown below.

public class TestFile{
    long id;
    byte[] content;
    /** setter and getter **/
}

Here you need to convert the content attribute and the Blob field of the database. At this time, you can use the typeHandler registered in the system——BlobTypeHandler to convert, as shown below.

<?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.ssm.chapter5.mapper.FileMapper">
    <resultMap type="com.ssm.chapter5.pojo.TestFile" id="file">
        <id column="id" property="id"/>
        <id column="content" property="content" typeHandler="org.apache.ibatis.type.BlobTypeHandler"/>
    </resultMap>

    <select id="getFile" parameterType="long" resultMap="file"> 
        select id, content from t_file where id = #{id}
    </select>

    <insert id="insertFile" parameterType="com.ssm.chapter5.pojo.TestFile">
        insert into t_file(content) values(#{content})
    </insert>
</mapper>

In fact, MyBatis can detect it without adding the typeHandler attribute of the bold code, and use the appropriate typeHandler for conversion.

In reality, loading a large amount of data into the JVM at one time will put a lot of pressure on the server, so you should consider using the file stream more often. At this time, just change the property content of POJO to InputStream.

If there is no typeHandler declaration, the system will detect and use BlobInputStream TypeHandler to convert the result for you. At this time, you need to modify the typeHandler in bold code to org.apache.ibatis.type.BlobInputStreamTypeHandler.

File operations are not commonly used on large Internet sites because of poor performance. More often, large-scale Internet sites will use the form of a file server and operate through a higher-speed file system. This is where you need to pay attention to building an efficient server.

Guess you like

Origin blog.csdn.net/unbelievevc/article/details/132311215