上一篇讲了StatementHandler,其中有ParameterHandler(参数处理器)是在StatementHandler被创建时被创建的。下面对ParameterHandler进行说明。其代码如下:

public interface ParameterHandler {
Object getParameterObject();
void setParameters(PreparedStatement ps) throws SQLException;
}

它只有两个方法,其中getParameterObject()是获取参数的,而setParameters()是设置参数的。

ParameterHandler只有一个实现类DefaultParameterHandler,在查看DefaultParameterHandler代码之前首先了解DefaultParameterHandler中的相关属性。代码如下所示:

//类型转换处理器:映射Java中数据类型与数据库中数据类型对应关系
private final TypeHandlerRegistry typeHandlerRegistry;
//映射sql语句与数据库操作对象关系以及sql关联的sql标签信息
private final MappedStatement mappedStatement;
//存储的需要进行赋值参数内容
private final Object parameterObject;
//输送的具体的sql语句
private final BoundSql boundSql;
//包含myBatis框架核心配置文件信息和sql映射文件信息
private final Configuration configuration;

下面查看DefaultParameterHandler中setParameters()的实现,代码如下所示:

  public void setParameters(PreparedStatement ps) {
ErrorContext.instance().activity("setting parameters").object(mappedStatement.getParameterMap().getId());
//// parameterMappings是对#{}里给出的参数信息的封装,即这个SQL是个参数化SQL时会存在(SQL语句中带占位符?)
List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
if (parameterMappings != null) {
for (int i = 0; i < parameterMappings.size(); i++) {
ParameterMapping parameterMapping = parameterMappings.get(i);
//存储过程才存在输出参数,所以当参数不是输出参数的时候,就需要设置
if (parameterMapping.getMode() != ParameterMode.OUT) {
Object value;
//这里的propertyName对应的是一个additionalParameters Map对象经过封装的key值,而不是Bean的属性
String propertyName = parameterMapping.getProperty();
//判断propertyName是additionalParameters中的key
if (boundSql.hasAdditionalParameter(propertyName)) {
value = boundSql.getAdditionalParameter(propertyName);
} else if (parameterObject == null) {
value = null;
}
//如果在typeHandlerRegistry中已经注册了这个参数的Class对象,value直接等于Method传进来的参数
else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
value = parameterObject;
}
//否则是Map或Bean,List或Array被封装成了Map,通过Key得到Value;Bean是通过封装的MataObject对象,Bean通过反射得到,再用propertyName得到相应的Value。
else {
MetaObject metaObject = configuration.newMetaObject(parameterObject);
value = metaObject.getValue(propertyName);
}
//得到parameterMapping的TypeHandler,均为IntegerTypeHandler
TypeHandler typeHandler = parameterMapping.getTypeHandler();
//得到相应parameterMapping的JdbcType,如果没有在#{}中显式的指定JdbcType,则为null
JdbcType jdbcType = parameterMapping.getJdbcType();
//当value和jdbcType都为null执行执行setNull操作时,会报OTHER的错误,因此指定JdbcType
if (value == null && jdbcType == null) {
jdbcType = configuration.getJdbcTypeForNull();
}
try {
//具体实现ps.set***
typeHandler.setParameter(ps, i + 1, value, jdbcType);
} catch (TypeException e) {
throw new TypeException("Could not set parameters for mapping: " + parameterMapping + ". Cause: " + e, e);
} catch (SQLException e) {
throw new TypeException("Could not set parameters for mapping: " + parameterMapping + ". Cause: " + e, e);
}
}
}
}
}

上面的的setParameter()是在BaseTypeHandler中实现的,它是IntegerTypeHandler等的父类,这里采用了模板模式。setParameter()的代码如下:

  public void setParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException {
if (parameter == null) {
if (jdbcType == null) {
throw new TypeException("JDBC requires that the JdbcType must be specified for all nullable parameters.");
}
try {
//执行PreparedStatement的setNull方法
ps.setNull(i, jdbcType.TYPE_CODE);
} catch (SQLException e) {
throw new TypeException("Error setting null for parameter #" + i + " with JdbcType " + jdbcType + " . " +
"Try setting a different JdbcType for this parameter or a different jdbcTypeForNull configuration property. " +
"Cause: " + e, e);
}
} else {
try {
//进行参数设置,是抽象方法,具体的实现在子类中
setNonNullParameter(ps, i, parameter, jdbcType);
} catch (Exception e) {
throw new TypeException("Error setting non null for parameter #" + i + " with JdbcType " + jdbcType + " . " +
"Try setting a different JdbcType for this parameter or a different configuration property. " +
"Cause: " + e, e);
}
}
}

下面对上面所说的setNull()进行说名:

public void setNull(int parameterIndex, int sqlType) throws SQLException{}
//parameterIndex:整形参数,第一个为1,第二个为2...
//sqlType必须为java.sql.Types 中定义的SQL类型代码
//若parameterIndex 不对应于 SQL 语句中的参数标记;发生数据库访问错误;或在关闭的 PreparedStatement上调用此方法,会抛出SQLException异常。

由上面代码知,当SQL类型代码为1111(OTHER)时,就会出现报错:java.sql.SQLException: 无效的列类型: 1111,解决方案是在其后加上jdbcType,示例代码如下:

<insert id="insertUser" parameterType="com.luis.domain.User">
insert into t_user(s_id,name,age)
values (
#{SId,jdbcType=INTEGER},
#{name,jdbcType=VARCHAR},
#{age,jdbcType=INTEGER}
);
</insert>

另有博主验证在ibatis2 可以正常的执行 数据库可以正常的插入数据。

参见:http://www.cnblogs.com/panxuejun/p/6163779.html

SqlSession对象之ParameterHandler的更多相关文章

  1. SqlSession对象之StatementHandler

    上一篇讲了SqlSession对象中的Executor,接下来将对SqlSession的另一个对象StatementHandler进行讲解. 一.StatementHandler介绍 Statemen ...

  2. mybatis的两个核心对象SqlSessionFactory和SqlSession对象

    mybatis的两个核心对象SqlSessionFactory和SqlSession对象 参见:https://www.cnblogs.com/wxdestiny/p/9743686.html

  3. 对 Service中sqlsession对象的优化

    在本线程中添加object数据,必须在本线程中才能获取出来..其他线程获取不到. public class Test { public static void main(String[] args) ...

  4. SqlSession对象之Executor

    Executor是Mybatis的一个核心接口,每一个SqlSession对象都会拥有一个Executor(执行器对象):这个执行对象负责[增删改查]的具体操作,我们可以简单的将它理解为JDBC中St ...

  5. 使用ThreadLocal管理Mybatis中SqlSession对象

    转自http://blog.csdn.net/qq_29227939/article/details/52029065 public class MybatisUtil { private stati ...

  6. SqlSession对象之ResultSetHandler

    ResultSetHandler是Mybatis中的另一重要接口,它的代码如下所示: public interface ResultSetHandler { <E> List<E&g ...

  7. 关于Mybatis与Spring整合之后SqlSession与mapper对象之间数量的问题。

    1,sqlsession的真实类型和数量 由于使用spring管理bean,当我们在代码中需要使用这个bean的时候,会首先去容器中找,第一次需要调用MapperFactoryBean的getObje ...

  8. MyBatis常用对象SqlSessionFactory和SqlSession介绍和运用

    学习框架一个比较好的路径阅读源码.本文介绍的SqlSessionFactory和SqlSession.可以通过了解SqlSessionFactory接口和SqlSession接口以及两个的实现类入手, ...

  9. MyBatis的2个核心对象:SqlSessionFactory、SqlSession

    SqlSessionFactory SqlSessionFactory是单个数据库映射关系经过编译后的内存镜像,主要作用是创建SqlSession. InputStream inputStream = ...

随机推荐

  1. Android开发教程 - 使用Data Binding(三)在Activity中的使用

    本系列目录 使用Data Binding(一)介绍 使用Data Binding(二)集成与配置 使用Data Binding(三)在Activity中的使用 使用Data Binding(四)在Fr ...

  2. FunDA(16)- 示范:整合并行运算 - total parallelism solution

    在对上两篇讨论中我们介绍了并行运算的两种体现方式:并行构建数据源及并行运算用户自定义函数.我们分别对这两部分进行了示范.本篇我准备示范把这两种情况集成一体的并行运算模式.这次介绍的数据源并行构建方式也 ...

  3. D13——C语言基础学PYTHON

    C语言基础学习PYTHON——基础学习D13 20180918内容纲要: 堡垒机运维开发 1.堡垒机的介绍 2.堡垒机的架构 3.小结 4.堡垒机的功能实现需求 1 堡垒机的介绍 百度百科 随着信息安 ...

  4. Linux inode空间占满 “no space left on device”

    Linux inode空间占满 提示 “no space left on device” 中文环境:“无法创建XXX目录,设备没有空间” Linux系统iNode耗尽硬盘无法写入文件怎么办?df -h ...

  5. Docker 创建 mysql 容器

    docker -v Docker version 18.06.1-ce, build e68fc7a   拉取 docker mysql 最新的镜像 docker pull mysql   Using ...

  6. Xamarin Forms MVVM实现效果说明

    实体对象定义Model2  和Model均可 实现响应效果 public class BaseModel : INotifyPropertyChanged { private bool _select ...

  7. 利用matlab求图像均值和方差的几种方法

    一.求均值 % 求一副灰度图像的均值 close all; clear; clc; i=imread('d:/lena.jpg'); %载入真彩色图像 i=rgb2gray(i); %转换为灰度图 i ...

  8. MVC3学习:利用jquery+ajax生成二维码(支持中文)

    二维码越来越热火了,做电子商务网站,不做二维码,你就OUT了. 一.下载DLL文件(ThoughtWorks.QRCode.dll),并在项目中引用.点此下载 如果你还不知道什么是QRCode二维码, ...

  9. Android的Fragment的第一种声明方式

    Android的Frangment的第一种声明方式 实际效果图如下: 项目结构图如下: fragment1: package com.demo.fragementfirst; import andro ...

  10. 自测 基础 js 脚本。

    <html> <head> <script> //function(<text>a{[]}lert('x')</text>)() docum ...