SqlSession对象之ParameterHandler
上一篇讲了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的更多相关文章
- SqlSession对象之StatementHandler
上一篇讲了SqlSession对象中的Executor,接下来将对SqlSession的另一个对象StatementHandler进行讲解. 一.StatementHandler介绍 Statemen ...
- mybatis的两个核心对象SqlSessionFactory和SqlSession对象
mybatis的两个核心对象SqlSessionFactory和SqlSession对象 参见:https://www.cnblogs.com/wxdestiny/p/9743686.html
- 对 Service中sqlsession对象的优化
在本线程中添加object数据,必须在本线程中才能获取出来..其他线程获取不到. public class Test { public static void main(String[] args) ...
- SqlSession对象之Executor
Executor是Mybatis的一个核心接口,每一个SqlSession对象都会拥有一个Executor(执行器对象):这个执行对象负责[增删改查]的具体操作,我们可以简单的将它理解为JDBC中St ...
- 使用ThreadLocal管理Mybatis中SqlSession对象
转自http://blog.csdn.net/qq_29227939/article/details/52029065 public class MybatisUtil { private stati ...
- SqlSession对象之ResultSetHandler
ResultSetHandler是Mybatis中的另一重要接口,它的代码如下所示: public interface ResultSetHandler { <E> List<E&g ...
- 关于Mybatis与Spring整合之后SqlSession与mapper对象之间数量的问题。
1,sqlsession的真实类型和数量 由于使用spring管理bean,当我们在代码中需要使用这个bean的时候,会首先去容器中找,第一次需要调用MapperFactoryBean的getObje ...
- MyBatis常用对象SqlSessionFactory和SqlSession介绍和运用
学习框架一个比较好的路径阅读源码.本文介绍的SqlSessionFactory和SqlSession.可以通过了解SqlSessionFactory接口和SqlSession接口以及两个的实现类入手, ...
- MyBatis的2个核心对象:SqlSessionFactory、SqlSession
SqlSessionFactory SqlSessionFactory是单个数据库映射关系经过编译后的内存镜像,主要作用是创建SqlSession. InputStream inputStream = ...
随机推荐
- 在Node中使用ES6语法
Node本身已经支持部分ES6语法,但是import export,以及async await(Node 8 已经支持)等一些语法,我们还是无法使用.为了能使用这些新特性,我们就需要使用babel把E ...
- tomcat 启动 证书异常java.io.IOException: Alias name [cas] does not identify a key entry
在搭建CAS server的过程中,Tomcat开启https,配置秘钥证书,证书是通过keytool生成的 <Connector port=" protocol="org. ...
- Git - 信息查看
git help git version # Display the version of git. git help # Prints the synopsis and a list of the ...
- Ubuntu14.04 + Text-Detection-with-FRCN(CPU)
操作系统: yt@yt-MS-:~$ cat /etc/issue Ubuntu LTS \n \l Python版本: yt@yt-MS-:~$ python --version Python pi ...
- WebDriver高级应用实例(9)
9.1封装操作表格的公用类 目的:能够使自己编写操作表格的公用类,并基于公用类进行表格中的元素的各类操作 被测网页的网址的HTML代码: <html> <body> <t ...
- odoo开发笔记 -- 异常信息处理汇总
1 Traceback (most recent call last): File , in _handle_exception return super(JsonRequest, self)._ha ...
- Identity Server4学习系列二之令牌(Token)的概念
1.简介 通过前文知道了Identity Server4的基本用途,现在必须了解一些实现它的基本细节. 2.关于服务端生成Token令牌 头部(Header): { “typ”: “JWT”, //t ...
- 六、CLR下的托管代码应用程序与非托管代码程序之间的性能对比
1.托管程序二次编译的问题,以及微软做的优化 五.CLR加载程序集代码时,JIT编译器对性能的产生的影响中介绍了CLR下托管应用程序的二次编译对性能产生的影响.事实上,在IL编译成本机代码的时候的时候 ...
- OSRM笔记
OSRM OSRM(OpenStreetMap Routeing Machine)可用于路线规划.作为高性能的路线规划引擎,OSRM使用C++14编写,基于开源的OpenStreetMap数据实现. ...
- Shell脚本 | 性能测试之启动时间
安卓应用的性能测试,通常包括六个指标:启动时间.内存.CPU.耗电量.流量.流畅度. 除了耗电量,其他五个指标的数据在我们团队中已经可以通过运行脚本的方式获取到. 今天给大家分享下启动时间的脚本吧- ...