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.
- Create a PreparedStatement interface with placeholders as follows:
PreparedStatement pstmt = connection.prepareStatement ("INSERT INTO STUDENTS(STUD_ID,NAME,EMAIL,DOB) VALUES(?,?,?,?)"); - 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());
- 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()); - And for the dob property, MyBatis will use the setDate() method for setting the dob place holder value.
- 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:
- 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));
}
} - We are using the ps.setString() and rs.getString() methods because the phone number is being stored in a VARCHAR type column.
- 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的更多相关文章
- 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 ...
- 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 ...
- MyBatis(3.2.3) - Configuring MyBatis using XML, Settings
The default MyBatis global settings, which can be overridden to better suit application-specific nee ...
- MyBatis(3.2.3) - Configuring MyBatis using XML, Properties
The properties configuration element can be used to externalize the configuration values into a prop ...
- 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 ...
- Mybatis增加对象属性不增加mapper.xml的情况
Mybatis增加对象属性不增加mapper.xml的情况: 只增加Model 对象的属性,在查询语句中返回相同名称的字段,但是在mapper中的 resultMap上面不进行新增字段的增加,查询结果 ...
- Mybatis学习总结(三)——SqlMapConfig.xml全局配置文件解析
经过上两篇博文的总结,对mybatis中的dao开发方法和流程基本掌握了,这一节主要来总结一下mybatis中的全局配置文件SqlMapConfig.xml在开发中的一些常用配置,首先看一下该全局配置 ...
- Java Persistence with MyBatis 3(中文版) 第三章 使用XML配置SQL映射器
关系型数据库和SQL是经受时间考验和验证的数据存储机制.和其他的ORM 框架如Hibernate不同,MyBatis鼓励开发者可以直接使用数据库,而不是将其对开发者隐藏,因为这样可以充分发挥数据库服务 ...
- Mybatis手工写sql语句及Mapper.xml方法
首先在项目中 建一个mapper包,然后在spring集合mybatis的配置文件中设置扫描这个mapper包 然后,建 封装查询结果需要的 pojo 然后,在 mapper包中创建 Mapper接口 ...
随机推荐
- qemu 模拟-arm-mini2440开发板-启动u-boot,kernel和nfs文件系统
qemu 本文介绍了如何编译u-boot.linux kernel,然后用qemu启动u-boot和linux kernel,达到与开发板上一样的学习效果! 虽然已经买了2440开发板,但是在实际学习 ...
- CentOS服务器配置发送邮件服务
CentOS服务器配置发送邮件服务 lsb_release -a 查看linux系统版本 在CentOS6以上版本自带mailx版本12.4 rpm -qa | grep mailx 查看系统自带的m ...
- Bootstrap栅格系统(布局)
栅格系统(布局) Bootstrap内置了一套响应式.移动设备优先的流式栅格系统,随着屏幕设备或视口(viewport)尺寸的增加,系统会自动分为最多12列. 我在这里是把Bootstrap中的栅格系 ...
- C#中Action和Func的使用
在日常使用delegate时,我们通常需要显示声明一个名为XXX的委托,而在使用Action委托时,不必显示定义一个封装无参数过程的委托. 比如正常使用delegate: using System; ...
- Cygwin解决Windows远程登录linux服务器
下载地址http://www.cygwin.com/install.html 选择mirror.htnshost.com网站下载的比较快. 安装Cygwin(/X)需要选择的包: openssh(必选 ...
- Android访问WebService的两种方法
首先解释一下WebService:WebService是一种基于SOAP协议的远程调用标准.通过WebService可以将不同操作系统平台,不同语言.不同技术整合到一起.详细见:http://baik ...
- stm32上的Lava虚拟机开发进度汇报(3)
感觉遇到一个瓶颈了,这几天都没有什么进度. 前几天把函数和一些最基本的伪指令实现了一下,能跑一点仅使用了绘图函数的lav,但是函数调用的问题一直没解决. 后来发现是粗心漏写了个++,解决了函数调用的问 ...
- 解决使用DevExpress开发错误:未将对象引用设置到对象的实例
在使用DevExpress是总是会出现一些状况.这次同事在他的机器上调试完成的代码发过来,却出现"未将对象引用设置到对象的实例"的错误,提示是Resources.resx的问题.另 ...
- STL中heap算法(堆算法)
①push_heap算法 以下是push_heap算法的实现细节.该函数接收两个迭代器,用来表现一个heap底部容器(vector)的头尾,而且新元素已经插入究竟部的最尾端. template ...
- Asp.Net页面(母版页)加载顺序
ASP.NET 母版页和内容页中的事件 母版页和内容页都可以包含控件的事件处理程序.对于控件而言,事件是在本地处理的,即内容页中的控件在内容页中引发事件,母版页中的控件在母版页中引发事件.控件事件不会 ...