欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

ibatis2与Spring2.5集成

程序员文章站 2022-04-19 23:52:57
...

代码即王道。集成方式有三种,详见JUnit4.x测试类的注释。。

首先是用到的实体类User.java

package com.jadyer.model;

import java.util.Date;

public class User {
	private Integer id;
	private String name;
	private Date birth;
	
	/*--三个属性的setter和getter略--*/
	
	public User(){}
	
	public User(Integer id, String name, Date birth){
		this.id = id;
		this.name = name;
		this.birth = birth;
	}
}

相应的实体类映射文件User.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMap      
    PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"      
    "http://ibatis.apache.org/dtd/sql-map-2.dtd">
<sqlMap namespace="User">
	<typeAlias alias="user" type="com.jadyer.model.User"/>
	
	<insert id="insertUser" parameterClass="user">
		insert into T_USER(id, name, birth) values(#id#, #name#, #birth#)
	</insert>
</sqlMap>

下面是位于CLASSPATH中的ibatis2.x的全局配置文件SqlMapConfig.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMapConfig      
    PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"      
    "http://ibatis.apache.org/dtd/sql-map-config-2.dtd">
<sqlMapConfig>

	<!-- 使用spring之后,数据源的配置移植到了spring上,所以iBATIS本身的配置可以取消 -->
	
	<sqlMap resource="com/jadyer/model/User.xml" />
</sqlMapConfig>

下面是位于CLASSPATH中的Spring2.5的全局配置文件applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-2.5.xsd 
	http://www.springframework.org/schema/tx   
	http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
		<property name="driverClassName" value="oracle.jdbc.OracleDriver"/>
		<property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:jadyer"/>
		<property name="username" value="scott"/>
		<property name="password" value="jadyer"/>
	</bean>
	
	<bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
		<property name="configLocation" value="classpath:SqlMapConfig.xml" />
		<property name="dataSource" ref="dataSource" />
	</bean>
	
	<bean id="userDao" class="com.jadyer.dao.ibatis.UserDaoIbatis">
		<property name="sqlMapClient" ref="sqlMapClient" />
	</bean>
	
	<!-- 声明一个事务管理器 -->
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>
	<!-- 声明一个已被纳入事务管理的DAO接口实现类的代理类 -->
	<bean id="userDaoProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
		<property name="transactionManager" ref="transactionManager" />
		<property name="target" ref="userDao" />
		<property name="transactionAttributes">
			<props>
				<prop key="insert*">PROPAGATION_REQUIRED</prop>
				<prop key="get*">PROPAGATION_REQUIRED,readOnly</prop>
			</props>
		</property>
	</bean>
</beans>

用到的操纵数据库表的接口UserDao.java

package com.jadyer.dao;

import java.util.List;

import com.jadyer.model.User;

public interface UserDao {
	public void insertUser(User user);
	
	/**
	 * 批量更新
	 */
	public void batchInsertUser(final List<User> userList, final String statement);
}

然后是该接口的实现类UserDaoIbatis.java


package com.jadyer.dao.ibatis;

import java.sql.SQLException;
import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.orm.ibatis.SqlMapClientCallback;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

import com.ibatis.sqlmap.client.SqlMapExecutor;
import com.jadyer.dao.UserDao;
import com.jadyer.model.User;

/**
 * SqlMapClientDaoSupport是Spring面向ibatis2.x的辅助类,它负责调度DataSource
 * SqlMapClientTemplate对传统SqlMapClient调用模式进行了封装,简化了上层访问代码
 * SqlMapClientTemplate能够完成ibatis操作,而DAO则通过对此类进行扩展获得上述功能
 */
public class UserDaoIbatis extends SqlMapClientDaoSupport implements UserDao {
	public void insertUser(User user) {
		getSqlMapClientTemplate().insert("insertUser", user);
	}
	
	public void batchInsertUser(final List<User> userList, final String statement) throws DataAccessException {
		getSqlMapClientTemplate().execute(new SqlMapClientCallback() {
			public Object doInSqlMapClient(SqlMapExecutor executor) throws SQLException {
				executor.startBatch();
				int batch = 0;
				for(User user : userList){
					executor.update(statement, user);
					batch++;
					if(200 == batch){ //每200条批量提交一次
						executor.executeBatch();
						batch = 0;
					}
				}
				executor.executeBatch();
				return null;
            }
        });
    }
}

接着是使用了JUnit4.x的单元测试类IbatisSpringTest.java

package com.jadyer.test;

import java.io.FileNotFoundException;
import java.sql.Date;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.jadyer.dao.UserDao;
import com.jadyer.model.User;

/**
 * Ibatis2.x与Spring的三种集成方式
 * @see ----------------------------------------------------------------------------------------------------------
 * @see 第一种:将sqlMapClient注入给继承了SqlMapClientDaoSupport类的DAO接口实现类
 * @see        示例代码,请见本例。并且此时不需要在DAO接口实现类中添加setSqlMapClient()方法
 * @see        优点是可以直接使用Spring封装后的getSqlMapClientTemplate,缺点是不便于移植
 * @see ----------------------------------------------------------------------------------------------------------
 * @see 第二种:将sqlMapClient注入给未继承任何类的DAO接口实现类
 * @see        此时需要在DAO接口实现类中增加setSqlMapClient(SqlMapClient sqlMapClient)方法
 * @see        然后我们就可以基于原生的iBATIS API来编程,而无需对Sprin*生任何依赖
 * @see ----------------------------------------------------------------------------------------------------------
 * @see 第三种:将sqlMapClientTemplate注入给DAO接口实现类
 * @see        此时需要在DAO接口实现类中增加setSqlMapClientTemplate(SqlMapClientTemplate sqlMapClientTemplate)方法
 * @see        <bean id="sqlMapClientTemplate" class="org.springframework.orm.ibatis.SqlMapClientTemplate">
 * @see        		<property name="sqlMapClient" ref="sqlMapClient" />
 * @see        </bean>
 * @see        <bean id="userDao" class="com.jadyer.dao.ibatis.UserDaoIbatis">
 * @see        		<property name="sqlMapClientTemplate" ref="sqlMapClientTemplate" />
 * @see        </bean>
 * @see ----------------------------------------------------------------------------------------------------------
 */
public class IbatisSpringTest {
	@Test
	public void insert() throws FileNotFoundException{
		ApplicationContext factory = new ClassPathXmlApplicationContext("applicationContext.xml");
//		UserDao userDao = (UserDao)factory.getBean("userDaoProxy"); //加入事务控制
		UserDao userDao = (UserDao)factory.getBean("userDao");      //未加事务控制
		User user = new User(22, "张起灵", Date.valueOf("2011-03-26"));
		userDao.insertUser(user);
	}
}

最后是用到的数据库脚本文件

-- Oracle 11g

-- Create table
create table t_user(
  id    number,
  name  varchar2(10),
  birth date
);