原文地址:mybatis-spring-1.0.0官方中文文档有误
作者:魏克塞爾
我最开始下的是mybatis-spring-1.0.0(由于当时没展开所有下载,只看到1.0.0,以为是最新),在整合过程中,我参考mybatis-spring-1.0.0-RC2-reference.pdf文档。配置SqlSession的过程中,我采用前几种方法都通过了测试。后面看到有SqlSessionTemplate,因为它是线程安全类,且能很好处理批量操作,后改为SqlSessionTemplate来注入SqlSession进行测试。
文档是提到:SqlSessionTemplate实现了SqlSession接口,下面是文档上的配置
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory" />
<constructor-arg index="1" value="BATCH" />
</bean>
</bean>
下面是我实现类的配置:
public class UserDaoImpl implements UserDao {
...........
}
其他配置也没问题,但启动容器后报两个错,一是注入的portalSqlSession不能转换为SqlSession类型,二是提示<constructor-arg index="1" value="BATCH" />这个有问题,应该是没这个构造参数。
我反复检查了代码,并阅读了官方文档三遍以上,还是觉得没错。文档上提到SqlSessionTemplate实现了SqlSession接口,那么我注入的SqlSessionTemplate是SqlSession实现类,不会有转换类型错误。但这个错误足足浪费了我下午三个小时
,百思不得其解。
![[转载]mybatis-spring-1.0.0官方中文文档有误](https://i-blog.csdnimg.cn/blog_migrate/a4c26d1e5885305701be709a3d33442f.gif)
下班后回到住所,仔细想了想,是不是SqlSessionTemplate不是SqlSession子类,我用反编译工具将mybatis-spring-1.0.0.jar包打开,一看源代码,我猜对。
部分源码码如下:
public class SqlSessionTemplate extends JdbcAccessor
implements SqlSessionOperations
{
private SqlSessionFactory sqlSessionFactory;
{
......
}
JdbcAccessor不是SqlSession子类
,SqlSessionOperations接口不是SqlSession接口。所以SqlSessionTemplate没有实现SqlSession。跟文档描述的不符。同时,构造参数也只有sqlSessionFactory一个参数,没有第二个参数,因些<constructor-arg index="1" value="BATCH" />也是错误的。
根据这些,我把private SqlSession portalSqlSession; 换成private SqlSessionTemplate portalSqlSession;并把<constructor-arg index="1" value="BATCH" />配置注释掉,容器启动通过,程序测试通过!
![[转载]mybatis-spring-1.0.0官方中文文档有误](https://i-blog.csdnimg.cn/blog_migrate/a4c26d1e5885305701be709a3d33442f.gif)
程序测试通过后,我还是想用上批量SqlSession,既然文档有写,那肯定有这功能,是不是有新版本实现了呢。我去官方去找(现在mybatis资源都放在googlecode上),便找到了mybatis-spring-1.0.2版本,此版本只有英文文档。反编译mybatis-spring-1.0.2原码,我直奔SqlSessionTemplate,发现SqlSessionTemplate不一样了。如下:
public class SqlSessionTemplate implements SqlSession
{
private final SqlSessionFactory sqlSessionFactory;
private final ExecutorType executorType;
private final SqlSession sqlSessionProxy;
private final PersistenceExceptionTran
slator exceptionTranslator;
{
}
SqlSessionTemplate实现了SqlSession接口,同时也有两个构造参数。马上恢复今天下午的代码,替换mybatis-spring-1.0.2.jar,程序顺利测试通过(长叹了一口气)
。
![[转载]mybatis-spring-1.0.0官方中文文档有误](https://i-blog.csdnimg.cn/blog_migrate/a4c26d1e5885305701be709a3d33442f.gif)
尔后,我又翻阅了1.0.0英文文档,发现1.0.0中文文档不相符,后查阅了1.0.2文档,发现1.0.2英文文档与1.0.0中文档吻合,估计是翻译的那位仁兄把版本弄错了。
如果要使用mybatis3与spring,建议使用mybatis-spring-1.0.2,此版本功能更强大,1.1.0应该还在开发中,官网只有mybatis-spring-1.1.0-SNAPSHOT.jar,里面只有源码。
下面附上mybatis3与spring3整合配置文档的主要部分,供挨踢友参考:
还是要感谢mybatis团队,不仅提供了优雅的持久层开源框架,还及时在官网上提供中文文档(虽然中文文档版本上出了点小纰漏),工作态度值得钦佩与学习。