类型处理器(类型转换器)
1.MyBatis自带一些常见的类型处理器
int - number
String - varchar()
2.自定义MyBatis类型处理器
java - 数据库(jdbc类型)
示例:
实体类Student 中:( Boolean–stuSex)
true:男
false:女
表student中: (int–stusex)
1:男
0:女
自定义类型转换器(boolean-int)步骤:
- 创建转换器:需要实现TypeHandler接口
TypeHandler接口有一个实现类BaseTypeHandler,因此 要实现转换器有两种选择:
(1).实现接口TypeHandler
(2).继承BaseTypeHandler
package com.ph.main.converter;
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;
public class BooleanAndIntConverter extends BaseTypeHandler<Boolean> {
//参数ResultSet为携带返回数据的容器,String:为表的列名
@Override
public Boolean getNullableResult(ResultSet arg0, String arg1) throws SQLException {
return arg0.getInt(arg1)==1?true:false;
}
//int:表示为第多少列
@Override
public Boolean getNullableResult(ResultSet arg0, int arg1) throws SQLException {
return arg0.getInt(arg1)==1?true:false;
}
//参数:PreparedStatement对象,int为PreparedStatement对象操作参数的位置,Boolean:java值(父类泛型对应)
@Override
public void setNonNullParameter(PreparedStatement arg0, int arg1, Boolean arg2, JdbcType arg3) throws SQLException {
if (arg2) {
arg0.setInt(arg1, 1);
}else {
arg0.setInt(arg1, 0);
}
}
//CallableStatement:存储函数,这里表示:从存储过程中根据第几列拿数据
@Override
public Boolean getNullableResult(CallableStatement arg0, int arg1) throws SQLException {
return arg0.getInt(arg1)==1?true:false;
}
}
2.配置conf.xml
<configuration>
<typeHandlers>
<typeHandler handler="com.ph.main.converter.BooleanAndIntConverter" javaType="boolean" jdbcType="INTEGER"/>
</typeHandlers>
<environments
。。。environments/>
</configuration>
3.配置Mapper.xml
当返回时:
<select id="queryStudenByIdtWithConverter" resultMap="queryOneC" parameterType="int">
select * from student where stunum=#{stuNum}
</select>
<!--type为返回值类型-->
<resultMap type="student" id="queryOneC">
<id property="stuNum" column="stunum"/>
<result property="stuName" column="stuname"/>
<result property="stuAge" column="stuage"/>
<result property="graName" column="graname"/>
<!--配置需要类型转换的属性-->
<result property="stuSex" column="stusex" javaType="boolean" jdbcType="INTEGER"/>
</resultMap>
当insert时:
<insert id="addStudent" parameterType="com.ph.main.dao.Student" >
insert into student(stunum,stuname,stuage,graname,stusex) values(#{stuNum},#{stuName},#{stuAge},#{graName},#{stuSex,javaType=boolean,jdbcType=INTEGER})
</insert>