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.

MyBatis(3.2.3) - Configuring MyBatis using XML, typeHandlers的更多相关文章

  1. MyBatis(3.2.3) - Configuring MyBatis using XML, Environment

    The key component of MyBatis is SqlSessionFactory from which we get SqlSession and execute the mappe ...

  2. MyBatis(3.2.3) - Configuring MyBatis using XML, typeAliases

    In the SQL Mapper configuration file, we need to give the fully qualified name of the JavaBeans for ...

  3. MyBatis(3.2.3) - Configuring MyBatis using XML, Settings

    The default MyBatis global settings, which can be overridden to better suit application-specific nee ...

  4. MyBatis(3.2.3) - Configuring MyBatis using XML, Properties

    The properties configuration element can be used to externalize the configuration values into a prop ...

  5. MyBatis(3.2.3) - Configuring MyBatis using XML, Mappers

    Mapper XML files contain the mapped SQL statements that will be executed by the application using st ...

  6. Mybatis增加对象属性不增加mapper.xml的情况

    Mybatis增加对象属性不增加mapper.xml的情况: 只增加Model 对象的属性,在查询语句中返回相同名称的字段,但是在mapper中的 resultMap上面不进行新增字段的增加,查询结果 ...

  7. Mybatis学习总结(三)——SqlMapConfig.xml全局配置文件解析

    经过上两篇博文的总结,对mybatis中的dao开发方法和流程基本掌握了,这一节主要来总结一下mybatis中的全局配置文件SqlMapConfig.xml在开发中的一些常用配置,首先看一下该全局配置 ...

  8. Java Persistence with MyBatis 3(中文版) 第三章 使用XML配置SQL映射器

    关系型数据库和SQL是经受时间考验和验证的数据存储机制.和其他的ORM 框架如Hibernate不同,MyBatis鼓励开发者可以直接使用数据库,而不是将其对开发者隐藏,因为这样可以充分发挥数据库服务 ...

  9. Mybatis手工写sql语句及Mapper.xml方法

    首先在项目中 建一个mapper包,然后在spring集合mybatis的配置文件中设置扫描这个mapper包 然后,建 封装查询结果需要的 pojo 然后,在 mapper包中创建 Mapper接口 ...

随机推荐

  1. UINavigationController切换controller动画设置

    http://blog.csdn.net/dabiaoyanjun/article/details/7774775 uinavigationcontrolleranimation在pushViewCo ...

  2. Codeforces Round #350 (Div. 2) E. Correct Bracket Sequence Editor (链表)

    题目链接:http://codeforces.com/contest/670/problem/E 给你n长度的括号字符,m个操作,光标初始位置是p,'D'操作表示删除当前光标所在的字符对应的括号字符以 ...

  3. c++的操作符格式记录

    以下摘自维基百科,mark一下,以备不时之需. For the purposes of this table, a, b, and c represent valid values (literals ...

  4. nginx 的安装

    一.必要软件准备1.安装pcre 为了支持rewrite功能,我们需要安装pcre 复制代码代码如下: # yum install pcre* //如过你已经装了,请跳过这一步 2.安装openssl ...

  5. 解决用Eclipse开发Android程序时不能生成R.java的问题

    今天我照着Mars老师的视频教程开始学习Android程序开发. 但是,我的Eclipse死活不能生成R.java文件,新建的工程也不行. 然后我百度,百度出来的结果一般是说这样解决: 1.clean ...

  6. 【M22】考虑以操作符复合形式(op=)取代其独身形式(op)

    1.对于内置类型,x = x+y 与x+=y的结果相同. 2. x=x+y 与 x+=y的结果相同,但二者做的事情差别很大. a.x=x+y做的事情:方法内有个局部对象,值为x+y,返回局部对象,返回 ...

  7. NFA与DFA

    正则表达式匹配,包含两个东西,一个是表达式,一个文本. NFA(Nondeterministic Finite Automaton),不确定有穷自动机,表达式主导,NFA去吃文本,贪婪算法吃下去,如果 ...

  8. EDIT Ini写Ini配置

    EDIT Ini写Ini配置  uses IniFiles; {$R *.dfm}   function IniFileName:string; begin    Result:=ExtractFil ...

  9. iOS开发——网络Swift篇&NSURLSession加载数据、下载、上传文件

    NSURLSession加载数据.下载.上传文件   NSURLSession类支持三种类型的任务:加载数据.下载和上传.下面通过样例分别进行介绍.   1,使用Data Task加载数据 使用全局的 ...

  10. unity工程接入Android sdk后真机测试解锁屏后退出的解决

    unity工程接入如91.移动支付等Android sdk后,真机运行尤其是在4.0+以上坏境,往往会出现解锁屏后退出的情况,解决办法如下: 可以在AndroidManifest.xml中所有的con ...