MyBatis(3.2.3) - Configuring MyBatis using XML, typeHandlers

As discussed in the previous chapter, MyBatis simplifies the persistent logic implementation by abstracting JDBC. MyBatis uses JDBC under the hood and provides simpler ways to implement database operations.

When MyBatis executes an INSERT statement by taking a Java object as an input parameter, it will create PreparedStatement and set the parameter values for the placeholders using the setXXX() methods.

Here XXX can be any one of Int, String, Date, and so on, based on the type of Java property.

An example is as follows:

<insert id="insertStudent" parameterType="Student">
    INSERT INTO STUDENTS(STUD_ID,NAME,EMAIL,DOB) VALUES(#{studId},#{name},#{email},#{dob})
</insert>

To execute this statement, MyBatis will perform the following sequence of actions.

  1. Create a PreparedStatement interface with placeholders as follows:
    PreparedStatement pstmt = connection.prepareStatement ("INSERT INTO STUDENTS(STUD_ID,NAME,EMAIL,DOB) VALUES(?,?,?,?)");
  2. Check the property type of studId in the Student object and use the appropriate setXXX method to set the value. Here studId is of the type integer, so it will use the setInt() method.
    pstmt.setInt(1,student.getStudId());
  3. Similarly, for the name and email attributes MyBatis will use the setString() methods because they are of the type String.
    pstmt.setString(2, student.getName());
    pstmt.setString(3, student.getEmail());
  4. And for the dob property, MyBatis will use the setDate() method for setting the dob place holder value.
  5. MyBatis first converts java.util.Date into java.sql.Timestamp and sets the value.
    pstmt.setTimestamp(4, new Timestamp((student.getDob()).getTime()));

Cool. But how does MyBatis know to use setInt() for the Integer and setString for the String type properties? MyBatis determines all these things using type handlers.

MyBatis comes with built-in type handlers for all primitive types, primitive wrapper types, byte[], java.util.Date, java.sql.Date, java.sql.Time, java.sql.Timestamp, java enums, and so on. So when MyBatis finds one of these types of properties, it uses the corresponding type handler to set the value on PreparedStatement, while at the same time populating the JavaBeans from the SQL Result Set.

 

What if we give a custom object type value to store into the database?

An example is as follows:

Assume that the STUDENTS table has a PHONE column that is of the type VARCHAR(15). The JavaBeans Student has the phoneNumber property of the PhoneNumber class.

public class PhoneNumber {
    private String countryCode;
    private String stateCode;
    private String number;

    public PhoneNumber() {
    }

    public PhoneNumber(String countryCode, String stateCode, String number) {
        this.countryCode = countryCode;
        this.stateCode = stateCode;
        this.number = number;
    }

    public PhoneNumber(String string) {
        if (string != null) {
            String[] parts = string.split("-");

            if (parts.length > 0) {
                this.countryCode = parts[0];
            }

            if (parts.length > 1) {
                this.stateCode = parts[1];
            }

            if (parts.length > 2) {
                this.number = parts[2];
            }
        }
    }

    public String getAsString() {
        return countryCode + "-" + stateCode + "-" + number;
    }

    // Setters and getters
}
public class Student {
    private Integer id;
    private String name;
    private String email;
    private PhoneNumber phone;

    // Setters and getters
}
<insert id="insertStudent" parameterType="Student">
    insert into students(name,email,phone) values(#{name},#{email},#{phone})
</insert>

Here, for the phone parameter we have given the value #{phone}; this gives the phone object that is of the type PhoneNumber. However, MyBatis doesn't know how to handle this type of object.

To let MyBatis understand how to handle custom Java object types, such as PhoneNumber, we can create a custom type handler as follows:

  1. MyBatis provides an abstract class BaseTypeHandler<T> that we can extend to create custom type handlers.
    package com.mybatis3.typehandlers;
    
    import java.sql.CallableStatement;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import org.apache.ibatis.type.BaseTypeHandler;
    import org.apache.ibatis.type.JdbcType;
    import com.mybatis3.domain.PhoneNumber;
    
    public class PhoneTypeHandler extends BaseTypeHandler<PhoneNumber> {
        @Override
        public void setNonNullParameter(PreparedStatement ps, int i, PhoneNumber parameter, JdbcType jdbcType) throws SQLException {
            ps.setString(i, parameter.getAsString());
        }
    
        @Override
        public PhoneNumber getNullableResult(ResultSet rs, String columnName) throws SQLException {
            return new PhoneNumber(rs.getString(columnName));
        }
    
        @Override
        public PhoneNumber getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
            return new PhoneNumber(rs.getString(columnIndex));
        }
    
        @Override
        public PhoneNumber getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
            return new PhoneNumber(cs.getString(columnIndex));
        }
    }
  2. We are using the ps.setString() and rs.getString() methods because the phone number is being stored in a VARCHAR type column.
  3. Once the custom type handler is implemented, we need to register it in mybatis-config.xml.
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
        <properties resource="application.properties"/>
        <typeHandlers>
            <typeHandler handler="com.mybatis3.typehandlers.PhoneTypeHandler"/>
        </typeHandlers>
    </configuration>

After registering PhoneTypeHandler, MyBatis will be able to store the Phone type object value into any VARCHAR type column.

 

posted on 2016-02-29 16:08  huey2672  阅读(646)  评论(0编辑  收藏  举报