`

ibatis+spring整合

阅读更多

说起这三个的整合,其实还是ibatis+spring的整合,好了,开始了!

Spring iBATIS整合实例这里介绍两种Spring iBATIS整合的方式,这两种整合方式也是spring官方文档中提到的这两种整合方案。

 

Spring iBATIS整合模式一

 

可以基于原生的iBATIS API来编程,而无需对Spring产生任何依赖。直接使用注入的 SqlMapClient

实例: 

 

Java代码 复制代码
  1. package net.chinaideal.samples.ibatis.dao;      
  2. import java.sql.SQLException;      
  3. import net.chinaideal.samples.ibatis.model.User;      
  4. import com.ibatis.sqlmap.client.SqlMapClient;      
  5. /**     
  6. * SpringiBatis - UserDAO.java      
  7. * 说明:     
  8. * UserDAO 实现     
  9. * 这个实现通过Spring维护iBatis的SqlMapClient,具体调用还是通过iBatis的API完成。     
  10. * 这样实现的有点是在不使用Spring的时,由于使用的都是iBatis的API,所以可移植性较好。     
  11. **/    
  12.   
  13. public class UserDAOImpl implements UserDAO {        
  14.     protected SqlMapClient sqlMapClient;              
  15.     public User getUserByUsername(String username) {             
  16.         try {                 
  17.     return (User) this.sqlMapClient.queryForObject("getUserbyUsername", username);             
  18.         } catch (SQLException ex) {                 
  19.             ex.printStackTrace();             
  20.         }             
  21.             return null;         
  22.     }          
  23.   
  24.     public SqlMapClient getSqlMapClient() {             
  25.             return sqlMapClient;         
  26.     }          
  27.     public void setSqlMapClient(SqlMapClient sqlMapClient){                         
  28.         this.sqlMapClient = sqlMapClient;         
  29.     }          
  30. }   
package net.chinaideal.samples.ibatis.dao;   
import java.sql.SQLException;   
import net.chinaideal.samples.ibatis.model.User;   
import com.ibatis.sqlmap.client.SqlMapClient;   
/**   
* SpringiBatis - UserDAO.java    
* 说明:   
* UserDAO 实现   
* 这个实现通过Spring维护iBatis的SqlMapClient,具体调用还是通过iBatis的API完成。   
* 这样实现的有点是在不使用Spring的时,由于使用的都是iBatis的API,所以可移植性较好。   
**/ 

public class UserDAOImpl implements UserDAO {     
	protected SqlMapClient sqlMapClient;           
	public User getUserByUsername(String username) {          
		try {              
	return (User) this.sqlMapClient.queryForObject("getUserbyUsername", username);          
		} catch (SQLException ex) {              
			ex.printStackTrace();          
		}          
			return null;      
	}       

	public SqlMapClient getSqlMapClient() {          
       		return sqlMapClient;      
	}       
	public void setSqlMapClient(SqlMapClient sqlMapClient){                      
		this.sqlMapClient = sqlMapClient;      
	}       
} 

  

 Spring iBATIS整合模式二 

 

Java代码 复制代码
  1. package net.chinaideal.samples.ibatis.dao;     
  2.     
  3. import net.chinaideal.samples.ibatis.model.User;      
  4. import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;     
  5.     
  6. /**    
  7.  * SpringiBatis - UserDAOImpl2.java    
  8.  
  9.  * 说明:    
  10.  * 模式2:UserDAOImpl2继承SqlMapClientDaoSupport类    
  11.  * SqlMapClientDaoSupport这个类为Spring的ibatis模版类    
  12.  * ibatis模版类提供很多模版方法,Spring提供了异常处理,使用比较方便。    
  13.  * 例如:    
  14.  * queryForObject(statename, args)等等。    
  15.  *    
  16.  * 但是这个方法用使用类Spring的SqlMapClientDaoSupport,所以需要Spring的支持简化了编码的过程,移植性不够。    
  17.  */    
  18.     
  19. public class UserDAOImpl2 extends SqlMapClientDaoSupport implements UserDAO {     
  20. /*  
  21. * 注意这里就不需要声明SqlMapClient 但在spring配置文件中写UserDAOImpl2这个bean时必须传入  
  22. * sqlMapClient的bean依赖   
  23. */  
  24.     public User getUserByUsername(String username) {     
  25.     return (User)getSqlMapClientTemplate().queryForObject("getUserbyUsername", username);     
  26.     }     
  27.     
  28. }   
package net.chinaideal.samples.ibatis.dao;  
 
import net.chinaideal.samples.ibatis.model.User;   
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;  
 
/**  
 * SpringiBatis - UserDAOImpl2.java  

 * 说明:  
 * 模式2:UserDAOImpl2继承SqlMapClientDaoSupport类  
 * SqlMapClientDaoSupport这个类为Spring的ibatis模版类  
 * ibatis模版类提供很多模版方法,Spring提供了异常处理,使用比较方便。  
 * 例如:  
 * queryForObject(statename, args)等等。  
 *  
 * 但是这个方法用使用类Spring的SqlMapClientDaoSupport,所以需要Spring的支持简化了编码的过程,移植性不够。  
 */ 
 
public class UserDAOImpl2 extends SqlMapClientDaoSupport implements UserDAO {  
/*
* 注意这里就不需要声明SqlMapClient 但在spring配置文件中写UserDAOImpl2这个bean时必须传入
* sqlMapClient的bean依赖 
*/
	public User getUserByUsername(String username) {  
    return (User)getSqlMapClientTemplate().queryForObject("getUserbyUsername", username);  
	}  
 
} 

 

Java代码 复制代码
  1. Spring的配置文件中则需要如下配置:   
  2.  <bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">   
  3.     <property name="configLocation" value="WEB-INF/sql-map-config.xml"/>   
  4.     <property name="dataSource" ref="dataSource"/>   
  5.  </bean>   
  6.   
  7. <bean id="userDao2" class="net.chinaideal.samples.ibatis.dao.UserDAOImpl2 ">   
  8.    <property name="sqlMapClient" ref="sqlMapClient"/>   
  9.  </bean>  
Spring的配置文件中则需要如下配置:
 <bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
    <property name="configLocation" value="WEB-INF/sql-map-config.xml"/>
    <property name="dataSource" ref="dataSource"/>
 </bean>

<bean id="userDao2" class="net.chinaideal.samples.ibatis.dao.UserDAOImpl2 ">
   <property name="sqlMapClient" ref="sqlMapClient"/>
 </bean>

 ------------------------------------

 

作为开源的Orm对象映射框架,ibatis是一个线程安全,学习容易,但是开发相对于hibernate来说的话,就要繁锁些,没有很好的工具支持ibatis所有的配置几乎是通过手写,这样增加了开发者的难度、、好啦,言归正转。下面编写实现。

一、引入spring,ibatis jar包.

二、编写log4j.properties日志文件

      log4j.rootLogger=DEBUG,stdout

      log4j.appender.stdout=org.apache.log4j.ConsoleAppender

      log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

      log4j.appender.stdout.layout.ConversionPattern=%c{1}% - %m%n

      log4j.logger.java.sql.PreparedStatement=DEBUG

三、建立Student.java类映象属性

 

Java代码 复制代码
  1. package org.terry.ibatis.pojo;   
  2.   
  3. public class Student {   
  4.   
  5.  private Long id;   
  6.  private String name;   
  7.  private String subject;   
  8.  private Long score;   
  9.   
  10.  public Long getId() {  return id; }   
  11.  public void setId(Long id) {  this.id = id; }   
  12.  public String getName() {  return name; }   
  13.  public void setName(String name) {  this.name = name; }   
  14.  public Long getScore() {  return score; }   
  15.  public void setScore(Long score) {  this.score = score; }   
  16.  public String getSubject() {  return subject; }   
  17.  public void setSubject(String subject) {  this.subject = subject; }   
  18. }   
  19.     
package org.terry.ibatis.pojo;

public class Student {

 private Long id;
 private String name;
 private String subject;
 private Long score;

 public Long getId() {  return id; }
 public void setId(Long id) {  this.id = id; }
 public String getName() {  return name; }
 public void setName(String name) {  this.name = name; }
 public Long getScore() {  return score; }
 public void setScore(Long score) {  this.score = score; }
 public String getSubject() {  return subject; }
 public void setSubject(String subject) {  this.subject = subject; }
}
  

四、编写 student.xml 映象文件

 

Xml代码 复制代码
  1. <?xml version="1.0" encoding="utf-8" ?>  
  2.   
  3. <!DOCTYPE sqlMap       
  4.     PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"  "http://ibatis.apache.org/dtd/sql-map-2.dtd">  
  5.   
  6. <sqlMap namespace="student">  
  7.   
  8.  <typeAlias alias="student" type="org.terry.ibatis.pojo.Student"/>  
  9.   
  10.  <resultMap class="student" id="studentResult">  
  11.   
  12.   <result property="id" column="id" jdbcType="number" javaType="java.lang.Long"/>  
  13.   <result property="name" column="name"/>  
  14.   <result property="subject" column="subject"/>  
  15.   <result property="score" column="score"/>  
  16.   
  17.  </resultMap>    
  18.   
  19.  <select id="selectAll" resultMap="studentResult">  
  20.   select * from student   
  21.  </select>    
  22.   
  23.  <select id="findbyId" parameterClass="java.lang.Long" resultClass="student">  
  24.   select * from student where id=#id#   
  25.  </select>  
  26.   
  27.  <insert id="insert" parameterClass="student">  
  28.   insert into student(id,name,subject,score) values(#id#,#name#,#subject#,#score#)   
  29.  </insert>  
  30.   
  31.  <update id="update" parameterClass="student">  
  32.   update student set name=#name#,subject=#subject#,score=#score# where id=#id#   
  33.  </update>  
  34.   
  35.  <delete id="delete" parameterClass="java.lang.Long">  
  36.   delete from student where id=#id#   
  37.  </delete>  
  38.   
  39. </sqlMap>  
<?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="student">

 <typeAlias alias="student" type="org.terry.ibatis.pojo.Student"/>

 <resultMap class="student" id="studentResult">

  <result property="id" column="id" jdbcType="number" javaType="java.lang.Long"/>
  <result property="name" column="name"/>
  <result property="subject" column="subject"/>
  <result property="score" column="score"/>

 </resultMap> 

 <select id="selectAll" resultMap="studentResult">
  select * from student
 </select> 

 <select id="findbyId" parameterClass="java.lang.Long" resultClass="student">
  select * from student where id=#id#
 </select>

 <insert id="insert" parameterClass="student">
  insert into student(id,name,subject,score) values(#id#,#name#,#subject#,#score#)
 </insert>

 <update id="update" parameterClass="student">
  update student set name=#name#,subject=#subject#,score=#score# where id=#id#
 </update>

 <delete id="delete" parameterClass="java.lang.Long">
  delete from student where id=#id#
 </delete>

</sqlMap>

 

五、编写 SqlMapConfig.xml文件【ibatis的配置文件中只剩下sqlMap了,其它都不要了】

Xml代码 复制代码
  1. <?xml version="1.0" encoding="utf-8" ?>  
  2.   
  3. <!DOCTYPE sqlMapConfig          
  4.     PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"        "http://ibatis.apache.org/dtd/sql-map-config-2.dtd">  
  5.      
  6. <sqlMapConfig>  
  7.     <sqlMap resource="org/terry/ibatis/pojo/student.xml"/>  
  8. </sqlMapConfig>  
<?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>
    <sqlMap resource="org/terry/ibatis/pojo/student.xml"/>
</sqlMapConfig>

 

 

六、编写 StudentDao.java(实现类)

 

Java代码 复制代码
  1. package org.terry.ibatis.dao;   
  2.   
  3. import java.io.IOException;   
  4. import java.sql.SQLException;   
  5. import java.util.List;   
  6. import org.springframework.beans.factory.xml.XmlBeanFactory;   
  7. import org.springframework.core.io.ClassPathResource;   
  8. import org.springframework.core.io.Resource;   
  9. import org.springframework.orm.ibatis.SqlMapClientCallback;   
  10. import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;   
  11. import org.terry.ibatis.pojo.Student;   
  12. import com.ibatis.sqlmap.client.SqlMapExecutor;   
  13.   
  14. public class StudentDao extends SqlMapClientDaoSupport implements Idao{   
  15.   
  16.  public void delete(Long id) {   
  17.   this.getSqlMapClientTemplate().delete("delete", id);   
  18.  }   
  19.   
  20.  public Object findbyId(Long id) {   
  21.   return this.getSqlMapClientTemplate().queryForObject("findbyId", id);   
  22.  }   
  23.   
  24.  public List getAll() {   
  25.   return (List)this.getSqlMapClientTemplate().execute(new SqlMapClientCallback(){   
  26.    public Object doInSqlMapClient(SqlMapExecutor sqlMapper) throws SQLException {   
  27.     return sqlMapper.queryForList("selectAll");   
  28.    }   
  29.   });   
  30.  }   
  31.   
  32.  public void save(Object o) {   
  33.   this.getSqlMapClientTemplate().insert("insert", o);   
  34.  }   
  35.   
  36.  public void update(Object o) {   
  37.   this.getSqlMapClientTemplate().update("update", o);   
  38.  }   
  39.   
  40.  public static void main(String[] args) throws IOException {   
  41.    Resource re=new ClassPathResource("Ibatis-Context.xml");   
  42.    XmlBeanFactory xml=new XmlBeanFactory(re);   
  43.    StudentDao student=(StudentDao)xml.getBean("studentDao");   
  44.   
  45.    Student stu=new Student();   
  46.    stu.setId(Long.valueOf(16));   
  47.    stu.setName("terry");   
  48.    stu.setScore(Long.valueOf(99));   
  49.    stu.setSubject("数学");   
  50.   
  51.    student.delete(Long.valueOf(16));   
  52.  }   
  53. }  
package org.terry.ibatis.dao;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.orm.ibatis.SqlMapClientCallback;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;
import org.terry.ibatis.pojo.Student;
import com.ibatis.sqlmap.client.SqlMapExecutor;

public class StudentDao extends SqlMapClientDaoSupport implements Idao{

 public void delete(Long id) {
  this.getSqlMapClientTemplate().delete("delete", id);
 }

 public Object findbyId(Long id) {
  return this.getSqlMapClientTemplate().queryForObject("findbyId", id);
 }

 public List getAll() {
  return (List)this.getSqlMapClientTemplate().execute(new SqlMapClientCallback(){
   public Object doInSqlMapClient(SqlMapExecutor sqlMapper) throws SQLException {
    return sqlMapper.queryForList("selectAll");
   }
  });
 }

 public void save(Object o) {
  this.getSqlMapClientTemplate().insert("insert", o);
 }

 public void update(Object o) {
  this.getSqlMapClientTemplate().update("update", o);
 }

 public static void main(String[] args) throws IOException {
   Resource re=new ClassPathResource("Ibatis-Context.xml");
   XmlBeanFactory xml=new XmlBeanFactory(re);
   StudentDao student=(StudentDao)xml.getBean("studentDao");

   Student stu=new Student();
   stu.setId(Long.valueOf(16));
   stu.setName("terry");
   stu.setScore(Long.valueOf(99));
   stu.setSubject("数学");

   student.delete(Long.valueOf(16));
 }
}

 

 

七、配置 ApplicationContext.xml文件

Xml代码 复制代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2.   
  3. <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">  
  4.   
  5. <beans>  
  6.   
  7.  <bean id="dataSource"  class="org.apache.commons.dbcp.BasicDataSource">  
  8.   
  9.      <property name="driverClassName">  
  10.            <value>oracle.jdbc.driver.OracleDriver</value>  
  11.    </property>  
  12.   
  13.   <property name="url">  
  14.           <value>jdbc:oracle:thin:@localhost:1521:orcl</value>  
  15.   </property>  
  16.   
  17.   <property name="username">  
  18.          <value>terry</value>  
  19.   </property>  
  20.   
  21.   <property name="password">  
  22.          <value>terry</value>  
  23.   </property>  
  24.   
  25.  </bean>  
  26.   
  27.  <bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">  
  28.       <property name="configLocation" value="SqlMapConfig.xml"/>  
  29.       <property name="dataSource" ref="dataSource"></property>  
  30.  </bean>  
  31.   
  32.     <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
  33.       <property name="dataSource" ref="dataSource"></property>  
  34.  </bean>  
  35.   
  36.   <!-- 配置事务拦截器 -->  
  37.    <bean id="transactionIterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor">  
  38.   
  39.     <!-- 事务拦截器需要注入一个事务管理器 -->  
  40.         <property name="transactionManager" ref="transactionManager"></property>  
  41.         <property name="transactionAttributes">  
  42.         <props>  
  43.               <prop key="insert*">PROPAGATION_REQUIRED</prop>  
  44.               <prop key="find*,get*">PROPAGATION_REQUIRED,readOnly</prop>  
  45.               <prop key="*">PROPAGATION_REQUIRED</prop>  
  46.      </props>  
  47.     </property>  
  48.    </bean>  
  49.    <bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">  
  50.   
  51.         <property name="beanNames">  
  52.              <list>  
  53.                   <value>*Dao</value>  
  54.              </list>  
  55.         </property>  
  56.   
  57.         <property name="interceptorNames">  
  58.              <list>  
  59.                   <value>transactionIterceptor</value>  
  60.              </list>  
  61.         </property>
    分享到:
    评论

相关推荐

    Struts2+iBATIS+Spring整合

    Struts2+iBATIS+Spring整合是Java Web开发中一种常见的技术栈组合,这三种框架协同工作,可以构建出高效、灵活的企业级应用。Struts2作为MVC(Model-View-Controller)架构的一部分,主要负责处理HTTP请求,管理前端...

    IBatis + spring 整合

    本教程将深入探讨如何将流行的持久层框架IBatis与Spring框架整合,以实现高效、灵活的数据访问。IBatis是一个轻量级的Java ORM(对象关系映射)框架,它允许开发者将SQL语句直接写在配置文件中,避免了JDBC代码的...

    ibatis+Spring+struts2整合实例

    本实例关注的是“ibatis+Spring+struts2”的整合,这是一个经典的Java Web开发组合,用于实现数据访问、业务逻辑控制和用户界面交互。下面我们将深入探讨这三个组件及其整合的关键知识点。 1. **iBATIS**:iBATIS...

    ibatis+spring+struts2 整合开发例子

    "ibatis+spring+struts2 整合开发例子"就是一个典型的Java Web应用集成开发案例,旨在帮助开发者理解和掌握这三大框架的协同工作原理。接下来,我们将详细讨论这三个组件以及它们的整合过程。 Ibatis是一个轻量级的...

    struts+iBATIS+spring整合例子

    Struts、iBATIS和Spring是Java开发中常用的三大框架,它们各自负责不同的职责,而将它们整合在一起,可以构建出高效、灵活的企业级应用程序。本文将深入探讨这三者的核心概念、整合过程以及实际应用。 **Struts** ...

    compass+ibatis+spring+struts2整合开发

    compass+ibatis+spring+struts2整合开发compass+ibatis+spring+struts2整合开发compass+ibatis+spring+struts2整合开发compass+ibatis+spring+struts2整合开发

    struts2+ibatis+spring+Hessian 整合项目

    struts2+ibatis+spring+Hessian 整合项目 web项目整合,服务端用hessian协议远程调用服务端的方法,hessian是用spring代理整合,struts2+ibatis+spring的整合项目,用作学习和开发基础平台构建很有用处,工程导入...

    基于struts2+ibatis+spring整合增删改查

    这个"struts2_iBATIS_spring"压缩包文件包含了整合这三个框架所需的源代码和配置文件,开发者可以通过学习和实践这些示例,加深对Struts2、iBATIS和Spring整合的理解,并运用到实际项目中。这种整合方式在Java Web...

    struts2+ibatis+spring框架整合

    struts2+ibatis+spring框架整合

    struts2+ibatis+spring 安例

    5. **整合iBatis与Spring**:通过Spring的SqlSessionFactoryBean,配置数据源和MyBatis的配置文件,将DAO接口与Mapper XML关联起来。 6. **部署与测试**:将所有配置文件、类库和应用代码打包成WAR文件,部署到应用...

    Struts2+ibatis+spring项目整合档示例.doc

    Struts2+ibatis+spring项目整合档示例.doc

    四个struts1(2)+spring+ibatis+jquery整合实例

    Struts1(2)+Spring+Ibatis+jQuery是一个经典的Java Web开发框架组合,它们各自在Web应用的不同层面上发挥着关键作用。这个整合实例旨在展示如何将这四个技术有效地结合在一起,创建一个高效、可维护的Web应用程序...

    struts2+hibernate+spring+ibatis+ext整合

    这个框架主要struts2+hibernate+spring+ibatis+ext整合,不要说hibernate和ibatis整合是多此一举哦,当你想用hibernate时把ibatis取了,用ibatis时把hibernate取了就可以了,这样很方便的!

    struts2+spring+ibatis+oracle整合的登陆系统

    这个"struts2+spring+ibatis+oracle整合的登陆系统"是一个完整的Web应用程序示例,它将这些组件融合在一起,实现了一个用户登录的功能。 首先,Struts2是基于Action的MVC框架,负责处理用户的请求并转发到相应的...

Global site tag (gtag.js) - Google Analytics