Myibatis和spring的集成(与事务配置) 二
昨天已经把主要的类和配置文件贴上了,今天来分析一下,我也是从用ibatis再到MyIbatis
用过来的,MyBatis 的前身就是 iBatis 两者还很有区别,也有很大的改进,MyBatis 对
sql的支持更好,更加灵活.
1.如何和spring集成到一起?
第一步肯定是在applicationContext.xml中增加相应的配置,有spring容器来管理
Myibatis,那么这个jar是必不可少的 mybatis-spring-1.0.1-SNAPSHOT.jar由于
Spring 3.0仅支持 iBatis2。那么,我们就想将 MyBatis3 的支持添加到 Spring3.0
中。不幸的是,Spring 3.0 的开发在 MyBatis 3.0 官方发布前就结束了。所以这个jar
不是spring官方的,应该是MyBatis团队的后续开发的在 MyBatis-Spring 中,
SqlSessionFactoryBean 是用于创建 SqlSessionFactory 的。要配置这个工bean,
放置下面的代码在 Spring 的 applicationContext.xml 配置文件中
<bean id="sqlSessionFactory" ref="dataSource" /><property name="configLocation" value="classpath:/config/ibatisConfig.xml" /><property name="typeAliasesPackage" value="com.ibatis.model" /><property name="mapperLocations" value="classpath*:com/ibatis/mapper/*.xml" /></bean><bean value="com.ibatis.dao" /></bean>
<typeHandlers><typeHandler javaType="Map" jdbcType="CURSOR" handler="com.ibatis.typeHandler.ResultSetTypeHandler"/></typeHandlers>
package com.ibatis.typeHandler;import java.sql.CallableStatement;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.ResultSetMetaData;import java.sql.SQLException;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import org.apache.commons.lang.StringUtils;import org.apache.ibatis.type.BaseTypeHandler;import org.apache.ibatis.type.JdbcType;/** * 存储过程的游标解析器 * @author wujj */public class ResultSetTypeHandler extends BaseTypeHandler<List<Map<String, Object>>> {@Overridepublic List<Map<String, Object>> getNullableResult(ResultSet arg0, String arg1) throws SQLException {return null;}@Overridepublic List<Map<String, Object>> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();ResultSet rs = (ResultSet) cs.getObject(columnIndex);if (!rs.isClosed()) {ResultSetMetaData data = rs.getMetaData();int columnCnt = data.getColumnCount();while (rs.next()) {Map<String, Object> rowMap = new HashMap<String, Object>();for (int i = 1; i <= columnCnt; i++) {String colName = data.getColumnName(i).toLowerCase();Object colValue = rs.getObject(colName);// TODO 类型处理rowMap.put(colName, colValue == null ? StringUtils.EMPTY : colValue.toString());}result.add(rowMap);}}return result;}@Overridepublic void setNonNullParameter(PreparedStatement arg0, int arg1, List<Map<String, Object>> arg2, JdbcType arg3) throws SQLException {}}