mybatis3.2.8 与 hibernate4.3.6 混用

混用是混合在一起使用,可以复用公共的配置。例如

a) mybatis与hibernate的sessionFactory,共用同一个dataSource
b) 事务管理共用hibernate的事务管理。

而不是使用mybatis和hibernate两个配置文件,使用mybatis就使用mybatis的配置文件里的配置,使用hibernate时就使用hibernate对应的配置。

原文链接:http://www.cnblogs.com/yjmyzz/p/4047823.html


为了防止原作者博客链接失效,复制一份原博。

mybatis、hibernate这二个框架各有特色,对于复杂的查询,利用mybatis直接手写sql控制起来更灵活,而一般的insert/update,hibernate比较方便。同一个项目中,这二个框架可以和谐共存,下面是一些步骤:

一、版本要求

Spring 4.11 + hibernate 4.3.6 + mybatis 3.2.8 + struts 2.3.16.3 (这是目前各框架的最新版本)

建议:如果用hibernate 4.x ,Spring最好也是4.x系列,否则getCurrentSession()容易报错。

二、pom.xml依赖项



    4.0.0
    infosky
    struts2-rest-ex
    war
    1.0
    
        1.6
        2.3.16.3
        4.1.1.RELEASE
        3.2.8
        4.3.6.Final
    
    

        
            commons-dbcp
            commons-dbcp
            1.4
        

        
        
            com.oracle
            ojdbc6
            11.2.0.3
        

        
            asm
            asm
            3.3.1
        

        
            asm
            asm-commons
            3.3.1
        

        
            asm
            asm-tree
            3.3.1
        

        
            commons-beanutils
            commons-beanutils
            1.8.3
        

        
            commons-collections
            commons-collections
            3.2.1
        

        
            commons-fileupload
            commons-fileupload
            1.3
        

        
            commons-io
            commons-io
            2.2
        

        
            org.apache.commons
            commons-lang3
            3.1
        

        
            javassist
            javassist
            3.12.1.GA
        

        
            ognl
            ognl
            3.0.6
        


        
        
            org.apache.logging.log4j
            log4j-api
            2.0.2
        
        
            org.apache.logging.log4j
            log4j-core
            2.0.2
        
        
            org.apache.logging.log4j
            log4j-web
            2.0.2
        
        
            org.slf4j
            slf4j-api
            1.7.7
        

        
            net.sf.ezmorph
            ezmorph
            1.0.6
        

        
            org.freemarker
            freemarker
            2.3.19
        

        
            org.codehaus.jackson
            jackson-core-asl
            1.9.10
        

        
            org.codehaus.jackson
            jackson-mapper-asl
            1.9.10
        

        
            net.sf.json-lib
            json-lib
            2.4
            jdk15
        

        
            org.apache.struts
            struts2-convention-plugin
            2.3.16
        

        
            org.apache.struts
            struts2-config-browser-plugin
            2.3.16
        

        
            org.apache.struts
            struts2-core
            ${struts2.version}
        

        
            org.apache.struts
            struts2-rest-plugin
            2.3.16
        

        
            com.thoughtworks.xstream
            xstream
            1.4.3
        

        
            org.apache.struts.xwork
            xwork-core
            ${struts2.version}
        

        
        
            javax.servlet
            servlet-api
            2.5
            provided
        

        
        
            org.apache.struts
            struts2-spring-plugin
            ${struts2.version}
        

        
            org.springframework
            spring-context
            ${spring.version}
        

        
            org.springframework
            spring-orm
            ${spring.version}
        

        
            org.springframework
            spring-beans
            ${spring.version}
        

        
            org.springframework
            spring-core
            ${spring.version}
        

        
            org.springframework
            spring-web
            ${spring.version}
        

        
            org.springframework
            spring-context
            ${spring.version}
        

        
            org.springframework
            spring-context-support
            ${spring.version}
        

        
            org.springframework
            spring-expression
            ${spring.version}
        

        
            org.springframework
            spring-jdbc
            ${spring.version}
        

        
            org.springframework
            spring-tx
            ${spring.version}
        

        
            org.springframework
            spring-aop
            ${spring.version}
        


        
            org.aspectj
            aspectjweaver
            1.7.3
        

        
            aopalliance
            aopalliance
            1.0
        


        
            junit
            junit
            4.11
        

        
        
            org.mybatis
            mybatis-spring
            1.2.2
        

        
            org.mybatis
            mybatis
            ${mybatis.version}
        

        
            com.github.miemiedev
            mybatis-paginator
            1.2.15
        

        
        
            org.hibernate
            hibernate-core
            ${hibernate.version}
        

        
            xml-apis
            xml-apis
            1.0.b2
            provided
        


    

    
        
            
            dev
            
                jdbc:oracle:thin:@172.21.129.51:1521:orcl
                ***
                ***
            
            
            
                true
            
        
        
            
            test
            
                jdbc:oracle:thin:@172.21.129.51:1521:orcl
                ***
                ***
            
        
    

    
        struts2-rest-ex
        
            
                src/main/resources
                true
            
        
        
            
                org.apache.maven.plugins
                maven-compiler-plugin
                2.5.1
                
                    1.6
                    1.6
                    utf-8
                
            
            
                maven-source-plugin
                2.1.2
                
                    
                        package
                        
                            jar-no-fork
                        
                    
                
            

            
                org.apache.maven.plugins
                maven-surefire-plugin
                2.16
                
                    once
                    -Dfile.encoding=UTF-8
                
            
        
    
    
        yjmyzz
        http://yjmyzz.cnblogs.com/
    



最终打包后,WEB-INF/lib下的jar文件列表为:

antlr-2.7.7.jar

aopalliance-1.0.jar
asm-3.3.1.jar
asm-commons-3.3.1.jar
asm-tree-3.3.1.jar
aspectjweaver-1.7.3.jar
commons-beanutils-1.8.3.jar
commons-collections-3.2.1.jar
commons-dbcp-1.4.jar
commons-fileupload-1.3.jar
commons-io-2.2.jar
commons-lang-2.3.jar
commons-lang3-3.1.jar
commons-logging-1.1.1.jar
commons-pool-1.5.4.jar
dom4j-1.6.1.jar
ezmorph-1.0.6.jar
freemarker-2.3.19.jar
hamcrest-core-1.3.jar
hibernate-commons-annotations-4.0.5.Final.jar
hibernate-core-4.3.6.Final.jar
hibernate-jpa-2.1-api-1.0.0.Final.jar
jackson-core-asl-1.9.10.jar
jackson-mapper-asl-1.9.10.jar
jandex-1.1.0.Final.jar
javassist-3.12.1.GA.jar
javassist-3.18.1-GA.jar
jboss-logging-3.1.3.GA.jar
jboss-logging-annotations-1.2.0.Beta1.jar
jboss-transaction-api_1.2_spec-1.0.0.Final.jar
json-lib-2.4-jdk15.jar
junit-4.11.jar
log4j-api-2.0.2.jar
log4j-core-2.0.2.jar
log4j-web-2.0.2.jar
mybatis-3.2.8.jar
mybatis-paginator-1.2.15.jar
mybatis-spring-1.2.2.jar
ognl-3.0.6.jar
ojdbc6-11.2.0.3.jar
slf4j-api-1.7.7.jar
spring-aop-4.1.1.RELEASE.jar
spring-beans-4.1.1.RELEASE.jar
spring-context-4.1.1.RELEASE.jar
spring-context-support-4.1.1.RELEASE.jar
spring-core-4.1.1.RELEASE.jar
spring-expression-4.1.1.RELEASE.jar
spring-jdbc-4.1.1.RELEASE.jar
spring-orm-4.1.1.RELEASE.jar
spring-tx-4.1.1.RELEASE.jar
spring-web-4.1.1.RELEASE.jar
struts2-config-browser-plugin-2.3.16.jar
struts2-convention-plugin-2.3.16.jar
struts2-core-2.3.16.3.jar
struts2-rest-plugin-2.3.16.jar
struts2-spring-plugin-2.3.16.3.jar
xmlpull-1.1.3.1.jar
xpp3_min-1.1.4c.jar
xstream-1.4.3.jar
xwork-core-2.3.16.3.jar

三、Spring配置(关键)




    
        
        
        
        
        
        
        
        
    

    
        
        
            
                com.cnblogs.yjmyzz.entity
            
        
        
            
                classpath*:hibernate/**/*.hbm.xml
            
        
        
            
                org.hibernate.dialect.Oracle10gDialect
                
                false
                true
                true
                3
                20
                20
                false
            
        
    

    
        
        
        
        
        
            
                
                    
                
            
        
    

    
        
    

    
        
            
        
    

    
        
            
            
        
    

    
        
        
    



有几个关键点:

a) mybatis与hibernate的sessionFactory,共用同一个dataSource

b) 事务管理共用hibernate的事务管理

四、web.xml配置 




    struts2-app-sample

    
        org.apache.logging.log4j.web.Log4jServletContextListener
    
    
        log4jServletFilter
        org.apache.logging.log4j.web.Log4jServletFilter
    
    
        log4jServletFilter
        /*
        REQUEST
        FORWARD
        INCLUDE
        ERROR
    

    
        contextConfigLocation
        classpath:spring.xml
    
    
        org.springframework.web.context.ContextLoaderListener
    

    
        struts2
        org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
        
            loggerFactory
            com.opensymphony.xwork2.util.logging.slf4j.Slf4jLoggerFactory
        
    

    
        openSessionInViewFilter
        org.springframework.orm.hibernate4.support.OpenSessionInViewFilter
        
            singleSession
            true
        
    

    
        struts2
        /*
    

    
        index.html
    



五、代码调用

5.1 服务层基类

package com.cnblogs.yjmyzz.service.support;
import java.io.Serializable;
import javax.annotation.Resource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.StatelessSession;


public class BaseServiceImpl implements Serializable {

    private static final long serialVersionUID = -33988360094493502L;

    /**
     * hibernate入口
     */
    @Resource(name = "sessionFactory")
    protected SessionFactory hibernateSessionFactory;


    /**
     * mybatis入口
     */
    @Resource(name = "sqlSessionFactory")
    protected SqlSessionFactory mybatisSessionFactory;


    protected Session openSession() {
        return hibernateSessionFactory.openSession();
    }


    protected StatelessSession openStatelessSession() {
        return hibernateSessionFactory.openStatelessSession();
    }


    protected Session getCurrentSession() {
        return hibernateSessionFactory.getCurrentSession();
    }


}

其它各业务服务实现类,都继承自它。当然,也可以弄一个BaseDAO,对hibernate做些封装

package com.cnblogs.yjmyzz.dao;

import java.io.Serializable;
import java.util.List;

/**
 * 基础数据库操作类
 * 
 * @author ss
 * 
 */
public interface BaseDAO {

    /**
     * 保存一个对象
     * 
     * @param o
     * @return
     */
    public Serializable save(T o);

    /**
     * 删除一个对象
     * 
     * @param o
     */
    public void delete(T o);

    /**
     * 更新一个对象
     * 
     * @param o
     */
    public void update(T o);

    /**
     * 保存或更新对象
     * 
     * @param o
     */
    public void saveOrUpdate(T o);

    /**
     * 查询
     * 
     * @param hql
     * @return
     */
    public List find(String hql);

    /**
     * 查询集合
     * 
     * @param hql
     * @param param
     * @return
     */
    public List find(String hql, Object[] param);

    /**
     * 查询集合
     * 
     * @param hql
     * @param param
     * @return
     */
    public List find(String hql, List param);

    /**
     * 查询集合(带分页)
     * 
     * @param hql
     * @param param
     * @param page
     *            查询第几页
     * @param rows
     *            每页显示几条记录
     * @return
     */
    public List find(String hql, Object[] param, Integer page, Integer rows);

    /**
     * 查询集合(带分页)
     * 
     * @param hql
     * @param param
     * @param page
     * @param rows
     * @return
     */
    public List find(String hql, List param, Integer page,
            Integer rows);

    /**
     * 获得一个对象
     * 
     * @param c
     *            对象类型
     * @param id
     * @return Object
     */
    public T get(Class c, Serializable id);

    /**
     * 获得一个对象
     * 
     * @param hql
     * @param param
     * @return Object
     */
    public T get(String hql, Object[] param);

    /**
     * 获得一个对象
     * 
     * @param hql
     * @param param
     * @return
     */
    public T get(String hql, List param);

    /**
     * select count(*) from 类
     * 
     * @param hql
     * @return
     */
    public Long count(String hql);

    /**
     * select count(*) from 类
     * 
     * @param hql
     * @param param
     * @return
     */
    public Long count(String hql, Object[] param);

    /**
     * select count(*) from 类
     * 
     * @param hql
     * @param param
     * @return
     */
    public Long count(String hql, List param);

    /**
     * 执行HQL语句
     * 
     * @param hql
     * @return 响应数目
     */
    public Integer executeHql(String hql);

    /**
     * 执行HQL语句
     * 
     * @param hql
     * @param param
     * @return 响应数目
     */
    public Integer executeHql(String hql, Object[] param);

    /**
     * 执行HQL语句
     * 
     * @param hql
     * @param param
     * @return
     */
    public Integer executeHql(String hql, List param);

} 
  

package com.cnblogs.yjmyzz.dao.impl;

import com.cnblogs.yjmyzz.dao.BaseDAO;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

@Component("baseDAO")
@SuppressWarnings("all")
public class BaseDAOImpl implements BaseDAO {

    private SessionFactory sessionFactory;

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    @Autowired
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    private Session getCurrentSession() {
        return sessionFactory.getCurrentSession();
    }

    public Serializable save(T o) {
        return this.getCurrentSession().save(o);
    }

    public void delete(T o) {
        this.getCurrentSession().delete(o);
    }

    public void update(T o) {
        this.getCurrentSession().update(o);
    }

    public void saveOrUpdate(T o) {
        this.getCurrentSession().saveOrUpdate(o);
    }

    public List find(String hql) {
        return this.getCurrentSession().createQuery(hql).list();
    }

    public List find(String hql, Object[] param) {
        Query q = this.getCurrentSession().createQuery(hql);
        if (param != null && param.length > 0) {
            for (int i = 0; i < param.length; i++) {
                q.setParameter(i, param[i]);
            }
        }
        return q.list();
    }

    public List find(String hql, List param) {
        Query q = this.getCurrentSession().createQuery(hql);
        if (param != null && param.size() > 0) {
            for (int i = 0; i < param.size(); i++) {
                q.setParameter(i, param.get(i));
            }
        }
        return q.list();
    }

    public List find(String hql, Object[] param, Integer page, Integer rows) {
        if (page == null || page < 1) {
            page = 1;
        }
        if (rows == null || rows < 1) {
            rows = 10;
        }
        Query q = this.getCurrentSession().createQuery(hql);
        if (param != null && param.length > 0) {
            for (int i = 0; i < param.length; i++) {
                q.setParameter(i, param[i]);
            }
        }
        return q.setFirstResult((page - 1) * rows).setMaxResults(rows).list();
    }

    public List find(String hql, List param, Integer page,
            Integer rows) {
        if (page == null || page < 1) {
            page = 1;
        }
        if (rows == null || rows < 1) {
            rows = 10;
        }
        Query q = this.getCurrentSession().createQuery(hql);
        if (param != null && param.size() > 0) {
            for (int i = 0; i < param.size(); i++) {
                q.setParameter(i, param.get(i));
            }
        }
        return q.setFirstResult((page - 1) * rows).setMaxResults(rows).list();
    }

    public T get(Class c, Serializable id) {
        return (T) this.getCurrentSession().get(c, id);
    }

    public T get(String hql, Object[] param) {
        List l = this.find(hql, param);
        if (l != null && l.size() > 0) {
            return l.get(0);
        } else {
            return null;
        }
    }

    public T get(String hql, List param) {
        List l = this.find(hql, param);
        if (l != null && l.size() > 0) {
            return l.get(0);
        } else {
            return null;
        }
    }

    public Long count(String hql) {
        return (Long) this.getCurrentSession().createQuery(hql).uniqueResult();
    }

    public Long count(String hql, Object[] param) {
        Query q = this.getCurrentSession().createQuery(hql);
        if (param != null && param.length > 0) {
            for (int i = 0; i < param.length; i++) {
                q.setParameter(i, param[i]);
            }
        }
        return (Long) q.uniqueResult();
    }

    public Long count(String hql, List param) {
        Query q = this.getCurrentSession().createQuery(hql);
        if (param != null && param.size() > 0) {
            for (int i = 0; i < param.size(); i++) {
                q.setParameter(i, param.get(i));
            }
        }
        return (Long) q.uniqueResult();
    }

    public Integer executeHql(String hql) {
        return this.getCurrentSession().createQuery(hql).executeUpdate();
    }

    public Integer executeHql(String hql, Object[] param) {
        Query q = this.getCurrentSession().createQuery(hql);
        if (param != null && param.length > 0) {
            for (int i = 0; i < param.length; i++) {
                q.setParameter(i, param[i]);
            }
        }
        return q.executeUpdate();
    }

    public Integer executeHql(String hql, List param) {
        Query q = this.getCurrentSession().createQuery(hql);
        if (param != null && param.size() > 0) {
            for (int i = 0; i < param.size(); i++) {
                q.setParameter(i, param.get(i));
            }
        }
        return q.executeUpdate();
    }

} 
  

至于mybatis,就没必要封装了,因为各xxxMapper接口,注入后可以直接拿来调

5.2 调用示例

package com.cnblogs.yjmyzz.service.support;

import java.math.BigDecimal;
import java.util.*;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cnblogs.yjmyzz.convertor.OrderConverter;
import com.cnblogs.yjmyzz.dao.BaseDAO;
import com.cnblogs.yjmyzz.dto.Order;
import com.cnblogs.yjmyzz.entity.TOrder;
import com.cnblogs.yjmyzz.mybatis.mapper.OrderMapper;
import com.cnblogs.yjmyzz.service.OrderService;

@Service
public class OrdersServiceImpl extends BaseServiceImpl implements OrderService {

    @Autowired
    OrderMapper orderMapper;

    @Resource
    BaseDAO tOrderDAO;

    private static final long serialVersionUID = 1513133416493770048L;

    @Override
    public Order get(String id) {
        // hibernate实现
        // return OrderConverter.toDto((TOrder) getCurrentSession().get(
        // TOrder.class, new BigDecimal(Integer.parseInt(id))));
        return OrderConverter.toDto(tOrderDAO.get(TOrder.class, new BigDecimal(
                Integer.parseInt(id))));

        // mybatis实现
        // return
        // OrderConverter.toDto(orderMapper.getOrder(Integer.parseInt(id)));
    }

    @Override
    public List getAll() {
        List entities = orderMapper.getAllOrder();
        List orders = new ArrayList();
        for (TOrder entity : entities) {
            orders.add(OrderConverter.toDto(entity));
        }
        return orders;
    }

    @Override
    public void doSave(Order order) {
        // hibernate
        TOrder entity = OrderConverter.toEntity(order);
        if (entity.getId() != null) {
            entity = (TOrder) getCurrentSession().get(TOrder.class,
                    entity.getId());

            // update fields
            entity.setClientname(order.getClientName());
            entity.setAmount(new BigDecimal(order.getAmount()));
        }
        getCurrentSession().saveOrUpdate(entity);
    }

    @Override
    public void doRemove(String id) {
        // mybatis
        orderMapper.deleteOrder(Integer.parseInt(id));

    }

}


其它注意事项:

hibernate 4.x以后,entity类上的注解,最好改成@Entity("TABLE_NAME"),而非以前的@Table(xxx),参考:

@Entity(name = "T_ORDER")
public class TOrder implements java.io.Serializable {

示例代码下载:struts-hibernate-mybatis-rest.zip 


你可能感兴趣的:(java·未分类)