三、类型处理器(类型转换器)

1.MyBatis自带一些常见的类型处理器
int - number

2.自定义MyBatis类型处理器
java -数据库(jdbc类型)

示例:
实体类Student :  boolean   stuSex  	
				true:false:女

表student:	number  stuSex
				1:0:

//步骤:
a.创建转换器:需要实现TypeHandler接口
通过阅读源码发现,此接口有一个实现类 BaseTypeHandler ,因此 要实现转换器有2种选择:
i.实现接口TypeHandler接口
ii.继承BaseTypeHandler

package com.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 BooleanAndInt extends BaseTypeHandler<Boolean>{

	@Override
	public void setNonNullParameter(PreparedStatement ps, int i,Boolean parameter, JdbcType jdbcType) throws SQLException {
		if(parameter) {
			ps.setInt(i,1);
		}else {
			ps.setInt(i,0);
		}
		
	}

	@Override
	public Boolean getNullableResult(ResultSet rs, String columnName) throws SQLException {
		// TODO Auto-generated method stub
		int sex=rs.getInt(columnName);
		return sex==1?true:false;
	}

	@Override
	public Boolean getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
		// TODO Auto-generated method stub
		int sex=rs.getInt(columnIndex);
		return sex==1?true:false;
	}

	@Override
	public Boolean getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
		// TODO Auto-generated method stub
		int sex=cs.getInt(columnIndex);
		return sex==1?true:false;
	}

}

b.配置conf.xml

//conf.xml
<typeHandlers>
	 	<typeHandler handler="com.converter.BooleanAndInt" javaType="Boolean" jdbcType="INTEGER"/>//注意:jdbc中INTEGER只能大写
</typeHandlers>
<environments default="development">
</environments>

c.配置mapper.xml

//mapper.xml
<select id="queryStudentByIdWithConverter" parameterType="int" resultMap="studentResult">//此处要用resultMap
		select * from student where id=#{id}
</select>
<resultMap type="student" id="studentResult">//type为java实体类名(此处为别名,实际为com.entity.student);id为此resultMap的标识
		<id property="id" column="id" />//id为主键映射;result为非主键映射property=实体类属性; column=字段名
		<result property="name" column="name"/>
		<result property="age" column="age"/>
		<result property="sex" column="sex" javaType="Boolean" jdbcType="INTEGER"/>
</resultMap>
发布了16 篇原创文章 · 获赞 0 · 访问量 231

猜你喜欢

转载自blog.csdn.net/BTLA_2020/article/details/105182507