`
jetway
  • 浏览: 480263 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

将Hibernate和iBatis两Orm框架整合,取长补短

    博客分类:
  • java
阅读更多

将Hibernate和iBatis两Orm框架整合,取长补短

 

由于Hibernate比较适合对数据进行增,删,改的操作,而iBatis适合进行数据 查询,批量操作,而且方便利用DB底层的功能,因此我尝试着持久层同时使用Hibernate和iBatis。

   以下是我BaseDaoImpl的代码:

Java代码 【转】将Hibernate和iBatis两Orm框架整合,取长补短 - jack-chen10 - baiyunxiaoxi的个人主页

 


package mypack.dao;   
  
import org.hibernate.SessionFactory;   
import org.springframework.orm.hibernate3.HibernateCallback;   
import org.springframework.orm.hibernate3.HibernateTemplate;   
import org.springframework.orm.ibatis.SqlMapClientTemplate;   
  
import com.ibatis.sqlmap.client.SqlMapClient;   
  
public abstract class BaseDaoImpl implements BaseDAO   
{   
    //iBatis的Template   
    private SqlMapClientTemplate sqlMapClientTemplate ;   
    //Hibernate的Template   
    private HibernateTemplate hibernateTemplate ;   
       
    //设置Hibernate   
    public final void setSessionFactory(SessionFactory sessionFactory); {   
        if(this.hibernateTemplate == null);{   
            this.hibernateTemplate = new HibernateTemplate(sessionFactory);;   
        }else{   
            this.hibernateTemplate.setSessionFactory(sessionFactory);;   
        }   
    }      
    //设置ibatis   
    public final void setSqlMapClient(SqlMapClient sqlMapClient); {   
        if(this.sqlMapClientTemplate == null);{   
            this.sqlMapClientTemplate = new SqlMapClientTemplate();;       
        }   
        this.sqlMapClientTemplate.setSqlMapClient(sqlMapClient);;   
    }   
       
    //获取Hibernate的模板   
    protected HibernateTemplate getHibernateTemplate();{   
       return hibernateTemplate   
    }   
    //获取iBatis的模板   
    protected SqlMapClientTemplate getSqlMapClientTemplate(); {   
        return sqlMapClientTemplate;   
    }   
  
    //一些Hibernate 的通用方法,   
    //当然也可不必声明,子类通过hibernateTemplate来操作   
  
    protected void save(Object object); {   
        hibernateTemplate.save(object);;   
    }   
    protected void saveOrUpdate(Object object); {   
        hibernateTemplate.saveOrUpdate(object);;   
    }   
  
    protected void update(Object object); {   
        hibernateTemplate.update(object);;   
    }   
    protected void delete(Object object);{   
        hibernateTemplate.delete(object);;   
    }   
    protected Object getObject(Class clazz, Serializable id);{   
        return hibernateTemplate.get(clazz, id);;   
    }   
       
    //子类通过iBatis 的sqlMapClientTemplate来操作   
}  

 

package mypack.dao;import org.hibernate.SessionFactory;

import org.springframework.orm.hibernate3.HibernateCallback;

import org.springframework.orm.hibernate3.HibernateTemplate;

import org.springframework.orm.ibatis.SqlMapClientTemplate;

import com.ibatis.sqlmap.client.SqlMapClient;

public abstract class BaseDaoImpl implements BaseDAO{

 //iBatis的Template

private SqlMapClientTemplate sqlMapClientTemplate ;

//Hibernate的Template

 private HibernateTemplate hibernateTemplate ;

//设置Hibernate

public final void setSessionFactory(SessionFactory sessionFactory); {

if(this.hibernateTemplate == null);{

this.hibernateTemplate = new HibernateTemplate(sessionFactory);

}else{ this.hibernateTemplate.setSessionFactory(sessionFactory);; }

 } //设置ibatis public final void setSqlMapClient(SqlMapClient sqlMapClient); {

if(this.sqlMapClientTemplate == null){

this.sqlMapClientTemplate = new SqlMapClientTemplate();

 }

this.sqlMapClientTemplate.setSqlMapClient(sqlMapClient);

 } //获取Hibernate的模板

protected HibernateTemplate getHibernateTemplate(){

 return hibernateTemplate

 }

//获取iBatis的模板

protected SqlMapClientTemplate getSqlMapClientTemplate()

{ return sqlMapClientTemplate; }

 //一些Hibernate 的通用方法, //当然也可不必声明,子类通过hibernateTemplate来操作

 protected void save(Object object){

hibernateTemplate.save(object);}

protected void saveOrUpdate(Object object){

hibernateTemplate.saveOrUpdate(object);

 } protected void update(Object object){

 hibernateTemplate.update(object);}

 protected void delete(Object object)

{ hibernateTemplate.delete(object);}

protected Object getObject(Class clazz, Serializable id){

 return hibernateTemplate.get(clazz, id); }

//子类通过iBatis 的sqlMapClientTemplate来操作

}

     即以组合方式,将HibernateTemplate和sqlMapClientTemplate集成起来,完成类似SqlMapClientDaoSupport和HibernateDaoSupport的工作,由于Java无法多类继承,所以只得以组合方式来做。不过Spring的两个Support代码不多,自己做满好,满好--记得这是梁家辉在《棋王》上最爱说说的:)

     在Spring中的主要配置是这样的:

   首先配置Hibernate的SessionFactory:

Java代码 【转】将Hibernate和iBatis两Orm框架整合,取长补短 - jack-chen10 - baiyunxiaoxi的个人主页

 


    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">        
    <!-- 引用上述定义的数据源 -->   
    <property name="dataSource">   
        <ref local="dataSource"/>   
    </property>   
       
    <!-- 定义Hibernate映射文件(资源) -->   
    <property name="mappingDirectoryLocations">   
        <list>   
            <value>classpath:/mypack</value>   
        </list>   
    </property>   
       
    <!-- 定义Hibernate配置属性 -->   
    <property name="hibernateProperties">   
        <props>   
            <prop key="hibernate.dialect">${hibernate.dialect}</prop>   
            <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>   
            <prop key="hibernate.cglib.use_reflection_optimizer">${hibernate.cglib.use_reflection_optimizer}</prop>   
        </props>   
    </property>   
    <property name="useTransactionAwareDataSource" value="true"></property>   
</bean>  

 

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <!-- 引用上述定义的数据源 --> <property name="dataSource"> <ref local="dataSource"/> </property> <!-- 定义Hibernate映射文件(资源) --> <property name="mappingDirectoryLocations"> <list> <value>classpath:/mypack</value> </list> </property> <!-- 定义Hibernate配置属性 --> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <prop key="hibernate.cglib.use_reflection_optimizer">${hibernate.cglib.use_reflection_optimizer}</prop> </props> </property> <property name="useTransactionAwareDataSource" value="true"></property> </bean>

    再是iBatis的sqlMapClient

Java代码 【转】将Hibernate和iBatis两Orm框架整合,取长补短 - jack-chen10 - baiyunxiaoxi的个人主页

 


<bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">   
    <property name="configLocation" value="sql-map-config.xml"/>   
    <property name="dataSource" ref="dataSource"/>       
    <property name="useTransactionAwareDataSource" value="true"></property>        
</bean>  

 

<bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean"> <property name="configLocation" value="sql-map-config.xml"/> <property name="dataSource" ref="dataSource"/> <property name="useTransactionAwareDataSource" value="true"></property> </bean>

     两者是useTransactionAwareDataSource属性都设置为ture,看Spring的Javadoc,说这可以在多Orm框架中保持事务的一致性,即通过DataSource关联,果真如此否?我还没有确定出来。

    事务管理器,用Hibernate的

Java代码 【转】将Hibernate和iBatis两Orm框架整合,取长补短 - jack-chen10 - baiyunxiaoxi的个人主页

 


        <!-- 事务处理的AOP配置 -->   
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">   
    <property name="sessionFactory">   
        <ref local="sessionFactory"/>   
    </property>   
</bean >   
  
<bean id="txProxyTemplate" abstract="true"    
        class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">        
    <!-- 指定事务管理器 -->   
    <property name="transactionManager" >   
        <ref local="transactionManager"/>   
    </property>   
       
    <!-- 指定业务策略 -->   
    <property name="transactionAttributes">   
      <props>   
         <prop key="get*">PROPAGATION_REQUIRED,readOnly</prop>   
         <prop key="add*">PROPAGATION_REQUIRED</prop>   
         <prop key="update*">PROPAGATION_REQUIRED</prop>   
         <prop key="delete*">PROPAGATION_REQUIRED</prop>   
      </props>   
    </property>   
</bean>     

 

<!-- 事务处理的AOP配置 --> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory"> <ref local="sessionFactory"/> </property> </bean > <bean id="txProxyTemplate" abstract="true" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"> <!-- 指定事务管理器 --> <property name="transactionManager" > <ref local="transactionManager"/> </property> <!-- 指定业务策略 --> <property name="transactionAttributes"> <props> <prop key="get*">PROPAGATION_REQUIRED,readOnly</prop> <prop key="add*">PROPAGATION_REQUIRED</prop> <prop key="update*">PROPAGATION_REQUIRED</prop> <prop key="delete*">PROPAGATION_REQUIRED</prop> </props> </property> </bean>

    然后做两个Dao,一个是CustomerDao,这个走Hibernate,直接看其实现:

Java代码 【转】将Hibernate和iBatis两Orm框架整合,取长补短 - jack-chen10 - baiyunxiaoxi的个人主页

 


   package mypack.dao;   
  
import mypack.Customer;   
  
public class CustomerDaoImpl extends BaseDaoImpl implements CustomerDao {   
  
    public void update(Customer customer); {   
        super.save(customer);;   
    }   
}  

 

package mypack.dao;import mypack.Customer;public class CustomerDaoImpl extends BaseDaoImpl implements CustomerDao { public void update(Customer customer); { super.save(customer);; }}

     再看OrderDao的实现,这个走iBatis(先分道扬镳,再殊途同归):

Java代码 【转】将Hibernate和iBatis两Orm框架整合,取长补短 - jack-chen10 - baiyunxiaoxi的个人主页

 


     package mypack.dao;   
  
import java.sql.SQLException;   
  
import org.springframework.orm.ibatis.SqlMapClientCallback;   
  
public class OrderDaoImpl extends BaseDaoImpl implements OrderDao {   
  /**  
   * update ibatis  
   */  
  public void updateOrderPrice(float rate);    
  {          
     getSqlMapClientTemplate();.update("updateOrderPrice",null);;   
  }   
}  

 

package mypack.dao;import java.sql.SQLException;import org.springframework.orm.ibatis.SqlMapClientCallback;public class OrderDaoImpl extends BaseDaoImpl implements OrderDao { /** * update ibatis */ public void updateOrderPrice(float rate); { getSqlMapClientTemplate();.update("updateOrderPrice",null);; }}

    再在一个Service中同时用这两上Dao完成一个事务:

Java代码 【转】将Hibernate和iBatis两Orm框架整合,取长补短 - jack-chen10 - baiyunxiaoxi的个人主页

 


    package mypack.service;   
  
import mypack.Customer;   
import mypack.dao.CustomerDao;   
import mypack.dao.OrderDao;   
  
public class CustomerServiceImpl implements CustomerService {   
  
    private CustomerDao customerDao;   
    private OrderDao orderDao;   
    public void updateCustomerAndOrder(Customer customer, float rate); {   
        customerDao.update(customer);;   
        orderDao.updateOrderPrice(rate);;   
    }   
    public CustomerDao getCustomerDao(); {   
        return customerDao;   
    }   
    public void setCustomerDao(CustomerDao customerDao); {   
        this.customerDao = customerDao;   
    }   
    public OrderDao getOrderDao(); {   
        return orderDao;   
    }   
    public void setOrderDao(OrderDao orderDao); {   
        this.orderDao = orderDao;   
    }   
}  

 

package mypack.service;import mypack.Customer;

import mypack.dao.CustomerDao;

import mypack.dao.OrderDao;

public class CustomerServiceImpl implements CustomerService {

private CustomerDao customerDao;

private OrderDao orderDao;

 public void updateCustomerAndOrder(Customer customer, float rate)

{ customerDao.update(customer);

orderDao.updateOrderPrice(rate);

 } public CustomerDao getCustomerDao(); { return customerDao; } public void setCustomerDao(CustomerDao customerDao); { this.customerDao = customerDao; } public OrderDao getOrderDao(); { return orderDao; } public void setOrderDao(OrderDao orderDao); { this.orderDao = orderDao; }}

     插入一条Customer记录,再Update所有Order(纯粹研究,没有实际意义)

   走:

Java代码 【转】将Hibernate和iBatis两Orm框架整合,取长补短 - jack-chen10 - baiyunxiaoxi的个人主页

 


package test.service;   
  
import org.apache.log4j.PropertyConfigurator;   
import org.springframework.context.ApplicationContext;   
import org.springframework.context.support.ClassPathXmlApplicationContext;   
  
public class SysInit   
{   
    public static ApplicationContext factory = null;   
    private static String[] filepath = {"applicationContext_service.xml"};   
    public static void init();   
    {   
        PropertyConfigurator.configure("D:\\personalWork\\proGroup\\hiTestPro\\src\\log4j.properties");;   
        if (factory == null);   
        {   
            try  
            {   
               factory = new  ClassPathXmlApplicationContext(filepath);;   
                   
  
            } catch (Exception e);   
            {   
                e.printStackTrace();;   
            }   
        }   
  
        try  
        {   
        } catch (Exception e);   
        {   
            e.printStackTrace();;   
        }   
    }   
  
    public static Object getBean(String name);   
    {   
        if (factory == null);   
        {   
            init();;   
        }   
        return factory.getBean(name);;   
    }   
  
    public static void main(String[] args);   
    {   
        SysInit.init();;   
    }   
}   
  
  
  
    package test.service;   
  
import junit.framework.TestCase;   
import mypack.Customer;   
import mypack.service.CustomerService;   
  
public class CustomerServiceTest extends TestCase {   
  
    protected void setUp(); throws Exception {   
        super.setUp();;   
        SysInit.init();;   
    }   
  
    protected void tearDown(); throws Exception {   
        super.tearDown();;   
    }   
       
    public void testupdateCustomerAndOrder();   
    {   
        CustomerService customerService = (CustomerService);SysInit.getBean("customerService");;   
        Customer customer = new Customer();;   
        customer.setId(3L);;   
        customer.setFirstname("xiong");;   
        customer.setLastname("hua");;   
        customer.setSex('F');;   
        customerService.updateCustomerAndOrder(customer, 2);;      
    }   
}  

 

package test.service;import org.apache.log4j.PropertyConfigurator;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class SysInit{ public static ApplicationContext factory = null; private static String[] filepath = {"applicationContext_service.xml"}; public static void init(); { PropertyConfigurator.configure("D:\\personalWork\\proGroup\\hiTestPro\\src\\log4j.properties");; if (factory == null); { try { factory = new ClassPathXmlApplicationContext(filepath);; } catch (Exception e); { e.printStackTrace();; } } try { } catch (Exception e); { e.printStackTrace();; } } public static Object getBean(String name); { if (factory == null); { init();; } return factory.getBean(name);; } public static void main(String[] args); { SysInit.init();; }} package test.service;import junit.framework.TestCase;import mypack.Customer;import mypack.service.CustomerService;public class CustomerServiceTest extends TestCase { protected void setUp(); throws Exception { super.setUp();; SysInit.init();; } protected void tearDown(); throws Exception { super.tearDown();; } public void testupdateCustomerAndOrder(); { CustomerService customerService = (CustomerService);SysInit.getBean("customerService");; Customer customer = new Customer();; customer.setId(3L);; customer.setFirstname("xiong");; customer.setLastname("hua");; customer.setSex('F');; customerService.updateCustomerAndOrder(customer, 2);; }}

       我测试了一下,如果iBatis的操作有问题,Customer也是没有办法插入了,所以基本上判断,这两个框架是可以做事务的。

 

Hibernate的缓存确实是一个问题,不过可以通过合理分配两者的工作来解决,比如Hibernate负责增删改,而ibatis只负责查询。
   目前我的应用就是简要列表查询的数据由iBatis负责获取,从简要列表进入后的操作由Hibernate负责。
   不过,如果这样限定后,也就没有必须管事务的事了。整合的目的只是为了提高Dao的内聚性并屏蔽掉具体实现。

 

  iBatis主要是可以将Sql和代码解耦,使Java代码更纯一些,而Hibernate有在查询数据时有一个不好的地方是,结果集中的记录要对应Domain Class,这就限制了结果集字段的灵活性,数据库中的结果集构造是很灵活的,而不是仅对应Domain Classs。另外Hibernate还要为每条结果集构造对象,数据缓存等工作,如果仅是查询,这种工作是没有必要而费时的。
   总之,我觉得Hibernate不太适合于构造简要列表时的查询,它的强项在于对一个Domain Class的增,删,改,查,而非业务数据查询。

分享到:
评论

相关推荐

    struts1+spring+hibernate+ibatis集成

    与Hibernate不同,iBatis不提供完整的ORM解决方案,而是将SQL和Java代码分离,使开发者有更大的灵活性来定制SQL查询。 这四个框架的集成通常按照以下步骤进行: 1. 配置Struts1:设置struts-config.xml,定义...

    spring与hibernate以及ibatis集成的实例和具体配置图解

    Spring作为容器,可以管理Hibernate和Ibatis的生命周期,通过Spring的DataSource、SessionFactory和SqlSessionFactoryBean等组件,实现对这两个数据访问层框架的配置和管理。 在压缩包子文件的文件名称列表中,我们...

    开发指南(spring,hibernate,ibatis,webwork)

    这四者在实际项目中经常结合使用,Spring可以整合Hibernate和iBatis作为数据访问层,而WebWork(或Struts2)则可以与Spring结合,形成强大的Web应用架构。`Manning@2007 - Spring in Action(2nd Edition).pdf`和`...

    struts2+hibernate+ibatis整合

    Struts2、Hibernate和iBatis是Java Web开发中三个非常重要的开源框架,它们分别用于MVC(模型-视图-控制器)架构、对象关系映射(ORM)和SQL映射。将这三个框架整合在一起可以构建高效、灵活的Web应用程序。 **...

    springmvc_hibernate_ibatis_jdbc

    标题中的"springmvc_hibernate_ibatis_jdbc"指的是一个整合了SpringMVC、Hibernate、iBatis和JDBC这四种关键技术的Java应用框架。这个框架旨在提供一个全面且强大的解决方案,便于开发人员进行Web应用程序的构建。 ...

    Spring MVC+Hibernate&Ibatis学习 例子 教程

    Spring MVC、Hibernate和iBatis是Java开发中常用的三大框架,它们在Web应用程序开发中各自承担着不同的职责。本教程将深入探讨这三个框架的核心概念、使用方法以及它们之间的协同工作。 **Spring MVC** 是Spring...

    Hibernate和IBatis对比

    其中,Hibernate与iBATIS作为两种最为知名的ORM框架,各有特点与应用场景。本文将深入探讨这两种框架的主要差异,并分析其各自的优缺点。 #### 二、概念介绍 1. **Hibernate**:当前最流行的ORM框架之一,提供了一...

    Struts2+spring+ibatis三大框架整合实例

    Struts2、Spring和iBatis是Java Web开发中常用的三大框架,它们分别负责MVC模式中的Action层、业务逻辑层和服务数据访问层。本文将详细介绍这三个框架如何整合,以及在实际项目中如何运用。 首先,Struts2作为表现...

    Struts2+Spring+Hibernate和Struts2+Spring+Ibatis

    Struts2+Spring+Hibernate和Struts2+Spring+Ibatis是两种常见的Java Web应用程序集成框架,它们分别基于ORM框架Hibernate和轻量级数据访问框架Ibatis。这两种框架结合Spring,旨在提供一个强大的、可扩展的、易于...

    ibatis和hibernate的区别

    在Java开发中,ibatis和Hibernate都是常见的对象关系映射(ORM)框架,它们简化了数据库操作,将Java对象与数据库表之间的映射关系抽象出来,使得开发人员可以使用面向对象的方式处理数据。然而,两者在设计理念和...

    iBatis和Hibernate的区别

    iBatis与Hibernate都是Java领域内流行的ORM(Object-Relational Mapping,对象关系映射)框架,用于简化Java应用程序与数据库之间的交互。尽管它们有着相似的目标,但在实现方式、设计理念等方面存在显著差异。 ###...

    struts2+ibatis+spring框架整合

    struts2+ibatis+spring框架整合

    访问数据库基本封装(spring/hibernate/ibatis)

    本篇文章将深入探讨三个流行的Java框架:Spring、Hibernate和iBatis,它们都提供了对数据库操作的高效封装,使得开发人员能够更便捷地处理数据库事务。 首先,Spring框架以其强大的依赖注入和面向切面编程闻名,它...

    spring,struts,hibernate,ibatis整合jar包大全

    在Java Web开发中,Spring、Struts、Hibernate和iBatis是四个非常重要的框架,它们分别负责不同层面的任务。Spring作为一个全面的轻量级框架,提供了依赖注入、AOP(面向切面编程)、MVC(模型-视图-控制器)等核心...

    ssh整合(spring+hibernate+ibatis)

    SSH整合是指将Spring、Hibernate和iBatis三个开源框架集成在一起,以实现高效、灵活的Web应用程序开发。Spring是核心的依赖注入(DI)和面向切面编程(AOP)框架,Hibernate则是一个强大的对象关系映射(ORM)工具,...

Global site tag (gtag.js) - Google Analytics