SoFunction
Updated on 2025-03-04

Detailed explanation of the usage tutorial of TypeHandler in MyBatis

1.TypeHandler function and usage scenarios

When we usually develop database operations, we sometimes report data type mismatch exceptions when we query and insert data when operating operations, and we can know that the data type is not unique. There must be multiple different data types. And we must be clear that Java, as a programming language, has its own data type, and the database also has its own data type.

jdbc data type: This enum is all database support types

Java data types: int, long, string,…

It is necessary to distinguish it clearly. For example, if the Java heavy date data is inserted into the database, it should have been converted into a certain type of the database, and it must have nothing to do with Java. There are some operations we cannot see in the middle that are used to process data.

Assuming that the java type at this time is the same as the database data type, how should I explain the date data in other languages ​​be inserted into the database? For example, C# operates the database storage time type, C# and java must have nothing to do with it. Therefore, there is a data type relationship between each language and the database.

think:

Because Java and the database have their own data types, we cannot see whether there are other operations before storing the java data into the database. Otherwise, how can we know which jdbc data type it matches?

Answer: The mybatis framework has made default relationship correspondence for each data type. All implementation classes of BaseTypeHandler are used to do these processing.

For example: Which type is jdbc when inserting date in java, and why is this type? What are the specific operations in the middle?

Answer: DateTypeHandler is to solve the processing of date data types.

2.TypeHandler use

When we want to customize the data type conversion of Java and JDBC, we need to implement the TypeHandler interface, the source code of this interface is as follows:

//This interface is used to specify the corresponding relationship between jdbc and java data types.public interface TypeHandler<T> {
  // Save operation, data processing before data is entered into the database  void setParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException;
  //The following three are the data processing before vo object encapsulation after loading data from the database  T getResult(ResultSet rs, String columnName) throws SQLException;
  T getResult(ResultSet rs, int columnIndex) throws SQLException;
  T getResult(CallableStatement cs, int columnIndex) throws SQLException;
}

JsonIntegerTypeHandler implements Integer and string transfer

public class JsonIntegerTypeHandler extends BaseTypeHandler<Integer> {
    private static final ObjectMapper mapper = new ObjectMapper();

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Integer parameter, JdbcType jdbcType) throws SQLException {
        (i, toJson(parameter));
    }

    @Override
    public Integer getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return ((columnName));
    }

    @Override
    public Integer getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return ((columnIndex));
    }

    @Override
    public Integer getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return ((columnIndex));
    }

    private String toJson(Integer params) {
        try {
            String copyObject = (params);
            return copyObject;
        } catch (Exception e) {
            ();
        }
        return "";
    }

    private Integer toObject(String content) {
        if (content != null && !()) {
            try {
                ("1111111111111"+content);
                return (Integer) (content, );
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else {
            return null;
        }
    }
}

Query

When querying, configure which field you transfer

    <resultMap  type="" >
        <result column="Time" property="timestamp" />

        <result column="type" jdbcType="INTEGER"
                property="type" typeHandler=""/>
        

    </resultMap>

  <select  resultMap="DmpDeviceReportResult">
        select trace_id, imei, topic, information, interaction_time,type
        from dmp_device_report_information
        where imei = #{serialNumber}
        <if test="beginTime != null and endTime != null">
            and interaction_time between #{beginTime} and #{endTime}
        </if>
        <if test="traceId != null and traceId != ''">
            and trace_id = #{traceId}
        </if>
        limit #{pageSize}  offset #{pageNum}
    </select>

New

<insert  parameterType="">
        INSERT INTO .dmp_device_report_information
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="null != type ">
                type,
            </if>
            <if test="null != traceId and '' != traceId">
                trace_id,
            </if>
            <if test="null != imei and '' != imei">
                imei,
            </if>
            <if test="null != topic and '' != topic">
                topic,
            </if>
            <if test="null != information and '' != information">
                information,
            </if>
            <if test="null != interactionTime  and '' != interactionTime ">
                interaction_time,
            </if>
            <if test="null != organizationId ">
                organization_id
            </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="null != type ">
                #{type,typeHandler= },
            </if>
            <if test="null != traceId and '' != traceId">
                #{traceId,typeHandler= },
            </if>
            <if test="null != imei and '' != imei">
                #{imei,typeHandler= },
            </if>
            <if test="null != topic and '' != topic">
                #{topic,typeHandler= },
            </if>
            <if test="null != information and '' != information">
                #{information,typeHandler= },
            </if>
            <if test="null != interactionTime and '' != interactionTime ">
                #{interactionTime,typeHandler= },
            </if>
            <if test="null != organizationId ">
                #{organizationId,typeHandler= },
            </if>
        </trim>
    </insert>

Used in mybatisPlus

Class annotation @TableName(autoResultMap = true)
Parameter annotation @TableField(typeHandler = )

@Data
@TableName(autoResultMap = true)
public class DmpDeviceReportInformation implements Serializable
{
    private static final long serialVersionUID = 1L;

    private Long id;

    /**
      * Message type 1: Message reporting 2: Message issuance
      */
 @TableField(typeHandler = )
    private Integer type;
    }

Note: If you use your own mapper query, you want to select the form of mybaits

If it wants to take effect overall

mybatis-plus:
   type-handlers-package: 

This is the article about the detailed explanation of the usage tutorial of TypeHandler in MyBatis. For more related content on MyBatis TypeHandler, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!