1.自带类型处理器
int——number等
2.自定义类型处理器
java——数据库(jdbc类型)
3.示例
实体类Student
boolean stuSex
true:男
false:女
表student
number stuSex
1:男
0:女
4.自定义类型转换器步骤
(1)创建转换器
通过阅读源码发现,此接口有一个实现类BaseTypeHandler ,因此要实现转换器有2种选择
a.实现接口TypeHandler接口
b.继承BaseTypeHandler
package nuc.hzb.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 BooleanAndNumberConverter extends BaseTypeHandler<Boolean> {
// set方法是java(Boolean)到db(Number)
@Override
public void setNonNullParameter(PreparedStatement ps, int i, Boolean parameter, JdbcType jdbcType)
throws SQLException {
// TODO Auto-generated method stub
if (parameter) {
// 如果是true,将该变量的值变成1
ps.setInt(i, 1);
} else {
// 如果是false,将该变量的值变成0
ps.setInt(i, 0);
}
}
@Override
public Boolean getNullableResult(ResultSet rs, String columnName) throws SQLException {
// TODO Auto-generated method stub
int sexNum = rs.getInt(columnName);
/*
* if (sexNum == 1) { return true; } else { return false; }
*/
return sexNum == 1?true:false;
}
@Override
public Boolean getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
// TODO Auto-generated method stub
int sexNum = rs.getInt(columnIndex);
return sexNum == 1?true:false;
}
@Override
public Boolean getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
// TODO Auto-generated method stub
int sexNum = cs.getInt(columnIndex);
return sexNum == 1?true:false;
}
}
(2)配置conf.xml
<typeHandlers>
<typeHandler handler="nuc.hzb.converter.BooleanAndNumberConverter" javaType="Boolean" jdbcType="INTEGER"/>
</typeHandlers>
需要注意的问题: jdbcType为INTEGER(大写)
(3)studentMapper.xml
<select id="queryStudentByStuno" parameterType="int" resultMap="studentResult">
select * from student where stuno = #{stuno}
</select>
<resultMap type="student" id="studentResult">
<!-- 分为主键id,非主键result -->
<id property="stuNo" column="stuno"/>
<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 id="addStudent" parameterType="student">
insert into student(stuno, stuname, stuage, graname, stusex) values(#{stuNo}, #{stuName}, #{stuAge}, #{graName}, #{stuSex, javaType=boolean, jdbcType=INTEGER})
</insert>
注意#{stuNo} 中存放的是属性值,需要严格区分大小写,可以通过id、result标签解决属性值和数据库存放的字段名不一致的问题
5.resultMap可以的实现功能
(1)类型转换
<resultMap type="student" id="studentResult">
...
</resultMap>
(2)属性和字段的映射关系
<id property="stuNo" column="stuno"/>
<result property="stuName" column="stuname"/>
<result property="stuAge" column="stuage"/>
<result property="graName" column="graname"/>
<result property="stuSex" column="stusex" javaType="boolean" jdbcType="INTEGER"/>