论坛首页 Java企业应用论坛

ibatis3整合spring

浏览 20124 次
精华帖 (0) :: 良好帖 (1) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2009-11-26   最后修改:2010-06-20
    以前一直从事hibernate教学工作,有几个学生说他们现在有某些时刻要用到ibatis,所有我也研究了一下。
不过我是从ibatis3学起,感觉比ibatis2爽多子。

    因为ibatis3现在还是测试版,spring也没有出相应的整合。所以,我根据spring整合hibernate的原理,也出来show一下,高手就不要笑我了。开工

主要是的文件有:
   Ibatis3SessionFactory.java      这个是由spring读取ibatis配置文件,并产生sessionFactory工厂的

    Ibatis3DaoSupport.java          我们的dao主要继承它了,因为它有一个模板类,定义了许多方法.

    IBatis3DaoTemplate.java         不是上面的说的模板类

    SqlSessionCallback.java          回调方法。

一 . 我们先来看一下Ibatis3SessionFactory.java
package com.ibatis3;

import java.io.IOException;
import java.io.Reader;

import javax.sql.DataSource;

import org.apache.ibatis.builder.xml.XMLConfigBuilder;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.defaults.DefaultSqlSessionFactory;
import org.apache.ibatis.transaction.managed.ManagedTransactionFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy;
/*
 *  session工厂类
 */
public class Ibatis3SessionFactory implements FactoryBean, InitializingBean {
	private String configLocation;

	private DataSource dataSource;

	private SqlSessionFactory sqlSessionFactory;

	private boolean useTransactionAwareDataSource = true;

	private String environmentId = "development";

	public void setEnvironmentId(String environmentId) {
		this.environmentId = environmentId;
	}

	public void setUseTransactionAwareDataSource(
			boolean useTransactionAwareDataSource) {
		this.useTransactionAwareDataSource = useTransactionAwareDataSource;
	}

	public Object getObject() throws Exception {
		return this.sqlSessionFactory;
	}

	public Class getObjectType() {
		return (this.sqlSessionFactory != null ? this.sqlSessionFactory
				.getClass() : SqlSessionFactory.class);
	}

	public boolean isSingleton() {
		return true;
	}

	public void afterPropertiesSet() throws Exception {
		this.sqlSessionFactory = this.buildSqlSessionFactory(configLocation);
	}
	protected SqlSessionFactory buildSqlSessionFactory(String configLocation)
			throws IOException {
		if (configLocation == null) {
			throw new IllegalArgumentException(
					"configLocation entry is required");
		}
		DataSource dataSourceToUse = this.dataSource;
		if (this.useTransactionAwareDataSource
				&& !(this.dataSource instanceof TransactionAwareDataSourceProxy)) {
			dataSourceToUse = new TransactionAwareDataSourceProxy(
					this.dataSource);
		}

		Environment environment = new Environment(environmentId,
				new ManagedTransactionFactory(), dataSourceToUse);

		Reader reader = Resources.getResourceAsReader(configLocation);
		XMLConfigBuilder parser = new XMLConfigBuilder(reader, null, null);
		Configuration config = parser.parse();
		config.setEnvironment(environment);

		return new DefaultSqlSessionFactory(config);
	}

	public DataSource getDataSource() {
		return dataSource;
	}

	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}

	public void setConfigLocation(String configLocation) {
		this.configLocation = configLocation;
	}
}

上面代码也借鉴了网络上部分代码,因为转来转去,也不知谁是原创。

二. 下面是最简单的回调函数:
package com.ibatis3;

import org.apache.ibatis.session.SqlSession;

public interface SqlSessionCallback {
	public Object doInSqlSession(SqlSession session);
}




三.模板类
  package com.ibatis3;

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

import javax.sql.DataSource;

import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.taglibs.standard.tag.common.sql.DataSourceUtil;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.jdbc.support.JdbcAccessor;
import org.springframework.transaction.support.TransactionSynchronizationManager;

public class IBatis3DaoTemplate extends JdbcAccessor {
	private SqlSessionFactory sessionFactory;

	public IBatis3DaoTemplate(SqlSessionFactory factory) {
		this.sessionFactory = factory;
	}

	public SqlSession openSession() {
		SqlSession session = (SqlSession) TransactionSynchronizationManager
				.getResource(sessionFactory);
		if (session == null) {
			session = sessionFactory.openSession();
		}
		return session;
	}

	public void setSessionFactory(SqlSessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public List executeFind(SqlSessionCallback callback) {
		return (List) execute(callback);
	}

	public Object execute(SqlSessionCallback callback) {

		SqlSession session = openSession();

		Object obj = callback.doInSqlSession(session);
		if (session != null)
			session.close();

		return obj;
	}

	// 删除,根据语句
	public int delete(final String statement) {
		return delete(statement, null);
	}

	// 删除,根据语句,带条件
	public int delete(final String statement, final Object param) {
		return (Integer) execute(new SqlSessionCallback() {

			public Object doInSqlSession(SqlSession session) {
				if (param != null)
					return session.delete(statement, param);
				else
					return session.delete(statement);
			}
		});
	}

	// 修改带条件
	public int update(final String statement, final Object param) {
		return (Integer) execute(new SqlSessionCallback() {

			public Object doInSqlSession(SqlSession session) {
				if (param != null)
					return session.update(statement, param);
				else
					return session.update(statement);
			}
		});
	}

	// 修改不带条件
	public int update(final String statement) {
		return update(statement, null);
	}

	// 增加带条件
	public int insert(final String statement, final Object param) {
		return (Integer) execute(new SqlSessionCallback() {

			public Object doInSqlSession(SqlSession session) {
				if (param != null)
					return session.insert(statement, param);
				else
					return session.insert(statement);
			}
		});
	}

	// 增加不带条件
	public int insert(final String statement) {
		return insert(statement, null);
	}

	// 查询分页
	public List selectList(final String statement, final Object param,
			final RowBounds bounds) {
		return executeFind(new SqlSessionCallback() {

			public Object doInSqlSession(SqlSession session) {
				if (statement == null)
					throw new IllegalArgumentException(
							"Sql 'statement' require");
				if (bounds != null && param != null)
					return session.selectList(statement, param, bounds);
				else if (bounds!=null)
					return session.selectList(statement, null, bounds);
				else if (param != null) {
					return session.selectList(statement, param);
				} 
			
				else
					return session.selectList(statement);

			}
		});
	}

	// 条件分页
	public List selectList(final String statement, final Object param,
			int skip, int limit) {
		return selectList(statement, param, new RowBounds(skip, limit));
	}

	// 查询不分页
	public List selectList(final String statement, final Object param) {
		return selectList(statement, param, null);
	}

	// 查询不带条件
	public List selectList(final String statement) {
		return selectList(statement, null);
	}

	// 条件查带处理查询结果,带分页
	public void select(final String statement, final Object param,
			final RowBounds bounds, final ResultHandler handler) {
		if (statement == null || handler == null)
			throw new IllegalArgumentException(
					"'statement' and 'handler' require");

		execute(new SqlSessionCallback() {

			public Object doInSqlSession(SqlSession session) {
				if (handler != null && bounds != null && param != null)
					session.select(statement, param, bounds, handler);
				else if (bounds == null)
					session.select(statement, param, handler);

				return null;
			}
		});
	}

	// 自己处理查询结果 ,不带分页
	public void select(final String statement, final Object param,
			final ResultHandler handler) {
		select(statement, param, null, handler);
	}

	// 查唯一结果
	public Object selectOne(final String statement) {
		return selectOne(statement, null);
	}

	// 查唯一结果带条件
	public Object selectOne(final String statement, final Object param) {
		if (statement == null)
			throw new IllegalArgumentException("Sql 'statement' require");
		return execute(new SqlSessionCallback() {

			public Object doInSqlSession(SqlSession session) {
				if (param != null)
					return session.selectOne(statement, param);
				else
					return session.selectOne(statement);

			}
		});
	}

}


 
四.Ibatis3DaoSupport支持类
  package com.ibatis3;

import org.springframework.dao.support.DaoSupport;

import org.springframework.transaction.support.TransactionSynchronizationManager;

import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSession;

import javax.sql.DataSource;
/*
 * Dao类
 * 主要接收传入的sessionFactory
 * 取得模板
 */
public class Ibatis3DaoSupport extends DaoSupport {
	private SqlSessionFactory sessionFactory;
	private IBatis3DaoTemplate template;
	
	public void createTemplate(){
		this.template = new IBatis3DaoTemplate(sessionFactory);
	}

	public IBatis3DaoTemplate getTemplate() {
		//System.out.println(template);
		return template;
	}

	public void setTemplate(IBatis3DaoTemplate template) {
		this.template = template;
	}

	//创建或得到session
	public SqlSession openSession() {

		SqlSession session = (SqlSession) TransactionSynchronizationManager
				.getResource(sessionFactory);
		if (session == null) {
			session = sessionFactory.openSession();
		}
     
		return session;
	}

	public SqlSessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SqlSessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
		this.template = new IBatis3DaoTemplate(sessionFactory);
		
	}

	
	@Override
	protected void checkDaoConfig() throws IllegalArgumentException {
		
		if (sessionFactory == null) {
			throw new IllegalArgumentException(
					"Property 'sessionFactory' or 'template'  is required");
		}

	}

}




五.ibatis配置文件,我放在src下面
  
    <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//ibatis.apache.org//DTD Config 3.0//EN"
                       "http://ibatis.apache.org/dtd/ibatis-3-config.dtd">

<configuration>
    <mappers>
      <mapper resource="com/pojos/Dep.xml"/>
   </mappers>
</configuration>

   

  很简单,就是装载些映射文件,其实可以sessionFactory中完成。

六.  pojo类和映射文件就不贴出了,请看附件

七.  spring的配置文件,用了声明式事务.
   
      <?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans  http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd  http://www.springframework.org/schema/aop  http://www.springframework.org/schema/aop/spring-aop-2.5.xsd  http://www.springframework.org/schema/tx  http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
	<!-- - - - - - - - Apache Dbcp Pool - - - - - - - -->
	<bean id="datasource"
		class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName"
			value="oracle.jdbc.driver.OracleDriver" />
		<property name="username" value="scott" />
		<property name="password" value="tiger" />
		<property name="url"
			value="jdbc:oracle:thin:@127.0.0.1:1521:ora92" />
	</bean>

	<!-- sqlMapClientSessionBean -->
	<bean id="sessionFactory"
		class="com.ibatis3.Ibatis3SessionFactory">
		<property name="configLocation" value="sqlMapConfig.xml"></property>
		<property name="dataSource" ref="datasource"></property>
	</bean>

	<!-- dao -->
	<bean id="depDao" class="com.dao.DepDaoImpl">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>

	<!-- - - - - - - spring Transaction Manager - - - - - - - -->
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="datasource" />
	</bean>
	<!-- - - - - - - spring Transaction Attribute - - - - - - - -->
	<tx:advice id="transactionAdvice"
		transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="*"/>
		</tx:attributes>
	</tx:advice>
	<!--******    weave  *********-->
	<aop:config>
		<aop:advisor advice-ref="transactionAdvice"
			pointcut="execution(* com.test.*.*(..))" />
	</aop:config>


</beans>

    


完整代码请下载下面附件,因本人水平有限,请勿用在生产环境:)

作者简介:[www.4yty.com 世外淘园站长]
  • src.rar (16.4 KB)
  • 下载次数: 1162
   发表时间:2009-11-26  
没工夫研究,还是等出稳定版本,不过还是要支持LZ的工作!
0 请登录后投票
   发表时间:2009-11-28  
楼主是株洲的?
0 请登录后投票
   发表时间:2009-11-28  
是株洲的。
不可以吗?呵呵。
0 请登录后投票
   发表时间:2009-11-28  
比2爽在哪里?我只用过2
0 请登录后投票
   发表时间:2009-11-28  
sw1982 写道
比2爽在哪里?我只用过2



比如说动态语言支持,ognl表达式,表关系一对多处理,不过对2研究不深。
从学习成本来说,3应该简单些。但现在稳定性应该是2
0 请登录后投票
   发表时间:2009-11-29  
用ibatis2好像没自己写session 工厂
0 请登录后投票
   发表时间:2010-01-22  
已有相关的issue和patch了
https://jira.springsource.org/browse/SPR-5991
貌似会在Spring 3.1 M1中发布
0 请登录后投票
   发表时间:2010-02-20  
十分期待完美支持,可以做些尝试了。
0 请登录后投票
   发表时间:2010-04-23  
ibator的东西也用上了?
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics