zoukankan      html  css  js  c++  java
  • spring整合mybatis

    spring整合mybatis的主要工作就是把mybatis框架使用中所涉及的核心组件配置到spring容器中,交给spring来创建和管理。spring可以接管mybatis配置信息的维护工作,我们选择把数据源配置和sql映射信息转移至spring配置文件中进行管理,以了解如何在spring中配置mybatis。

    由于spring3的开发在mybatis3官方发布之前就结束了,spring开发团队不想发布一个基于非发布版本的mybatis的整合支持,因此spring3并没有提供对mybatis3的支持。为了使spring3支持mybatis3,mybatis团队按照spring集成orm框架的统一风格开发了相关整合组件,方便开发者在spring中集成使用mybatis。即使用mybatis-spring依赖。

    spring-jdbc依赖是spring对数据源的支持,spring-tx依赖是spring对事物的支持。

    mapper文件如下

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE mapper PUBLIC 
            "-//mybatis.org//DTD Mapper 3.0//EN" 
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="edu.cn.dao.UserMapper">
    <select id="getUserList" resultMap="userList" parameterType="User"> select u.*, r.roleName from smbms_user u, smbms_role r where u.userName like connect ('%', #{userName}, '%') and u.userRole=#{userRole} and u.userRole=r.id </select> <resultMap id="userList" type="User"> <result property="userRoleName" column="roleName"/> </resultMap> </mapper>

    mybatis配置文件如下

    <?xml version="1.0" encoding="UTF-8"?>
            <!DOCTYPE configuration PUBLIC
                    "-//mybatis.org//DTD Config 3.0//EN"
                    "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
        <typeAliases>
            <package name="edu.cn.pojo"/>
        </typeAliases>
    </configuration>

    spring配置文件如下

    配置DataSource

    在spring配置数据源,首先要选择一种具体的数据源实现技术,目前流行的数据源实现有dbcp、c3p0、Proxool等,它们都实现了连接池功能。以dbcp数据源为例,dbcp数据源隶属于apache commons项目,使用dbcp数据源需要添加commons-dbcp和commons-pool依赖。

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url">
            <value><![<![CDATA[
                jdbc:mysql://127.0.0.1:3306/smbms?useUnicode=true&characterEncoding=utf-8            
            ]]></value>
        </property>
        <property name="username" value="root"/>
        <property name="password" value="123"/>
    </bean>

    因为url属性的值包含特殊符号“&”,所以赋值时使用了<![CDATA[]]标记,也可将其替换为实体引用“&amp;”,如下所示

    <property name="url" value="jdbc:mysql://127.0.0.1:3306/smbms?useUnicode=true&amp;characterEncoding=utf-8"/>

    配置SqlSessionFactoryBean

    在mybatis中,SqlSessionFactory的实例需要使用SqlSessionFactoryBuilder创建,而在集成环境中,则可以使用mybatis-spring整合包中的SqlSessionFactoryBean来代替。SqlSessionFactoryBean封装了使用SqlSessionFactoryBuilder创建SqlSessionFactory的过程,我们可以在spring中以配置文件的形式,通过配置SqlSessionFactoryBean获得SqlSessionFactory实例。

    <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="mapperLocations" value="classpath:edu/cn/dao/**/*.xml"></property>
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
    </bean>

    classpath:edu/cn/dao/**/*.xml表示扫描edu.cn.dao包及其任意层级子包中任意名称的xml类型的文件

    除了数据源和sql映射信息,其他的mybatis配置信息也可以转移至spring配置文件中进行维护,只需要通过SqlSessionFactoryBean的对应属性进行赋值即可。

    使用SqlSessionTemplate进行持久化操作

    在集成环境中,为了更好的使用SqlSession,充分利用spring框架提供的服务,mybatis-spring依赖提供了SqlSessionTemplate类。SqlSessionTemplate类实现了mybatis的SqlSession接口,可以替换mybatis中原有的SqlSession实现类来提供数据库访问操作。使用SqlSessionTemplate可以更好的与spring服务融合并简化部分流程化的工作,还可以保证和当前spring事务相关联、自动管理会话的生命周期,包括必要的关闭、提交和回滚操作。

    public class UserMapperImpl implements UserMapper{
        private SqlSessionTemplate sqlSession;
    
        @Override
        public List<User> getUserList(User user){
            return sqlSession.selectList("edu.cn.dao.UserMapper.getUserList", user);
        }
    
        public SqlSessionTemplate getSqlSession(){
            return sqlSession;
        }
    
        public void setSqlSession(SqlSessionTemplate sqlSession){
            this.sqlSession = sqlSession;
        }
    }
    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactoryBean"/>
    </bean>
    
    <bean id="userMapper" class="edu.cn.dao.UserMapperImpl">
        <property name="sqlSession" ref="sqlSessionTemplate"/>
    </bean>

    创建SqlSessionTemplate实例时,需要通过其构造方法注入SqlSessionFactory实例。

    与mybatis中默认的SqlSession实现不同,SqlSessionTemplate是线程安全的,可以以单例模式配置并被多个dao对象共用,而不必为每个dao单独配置一个SqlSessionTemplate实例

    业务层

    public class UserServiceImpl implements UserService{
        private UserMapper userMapper;
    
        @Override
        public List<User> findUsersWithConditions(User user){
            try{
                return userMapper.getUserList(user);
            }catch(RuntimeException e){
                e.printStackTrace();
                throw e;
            }
        }
    
        public UserMapper getUserMapper(){
            return userMapper;
        }
    
        public void setUserMapper(UserMapper userMapper){
            this.userMapper = userMapper;
        }
    }
    <bean id="userService" class="edu.cn.dao.UserServiceImpl">
        <property name="userMapper" ref="userMapper"/>
    </bean>

    测试

    ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext-jdbc.xml");
    UserService userService = (UserService) ctx.getBean("userService");
    User userCondition = new User();
    userCondition.setUserName("ygb");
    userCondition.setUserRole(3);
    List<User> userList = new ArrayList<Usre>();
    userList = userService.findUsersWithConditions(userCondition);
    for (User userResult : userList) {
        logger.debug("testGetUserList userCode:"
            + userResult.getUserCode() + "and userName:"
            + userResult.getUserName() + "and userRole:"
            + userResult.getUserRole() + "and userRoleName:"
            + userResult.getUserRoleName() + "and address:"
            + userResult.getAddress());
    }

    mybatis-spring依赖提供了SqlSessionDaoSupport类来简化SqlSessionTemplate的配置和获取,如下

    public class UserMapperImpl extends SqlSessionDaoSupport
                 implements UserMapper{
        @Override
        public List<User> getUserList(User user){
            return this.getSqlSession().selectList("edu.cn.dao.UserMapper.getUserList", user);
        }
    }        

    此时,spring配置文件中就无需配置SqlSessionTemplate了。

    SqlSessionDaoSupport类提供了setSqlSessionFactory()方法用来注入SqlSessionFactory实例并创建SqlSessionTemplate实例,同时提供了getSqlSession()方法用来返回创建好的SqlSessionTemplate实例。

  • 相关阅读:
    C# 数组冒泡排序复习
    在建工程转固流程
    增强 | 屏幕增强的实现 (事务代码:MM01) 转自ABAP之家
    MM | 采购订单中不同的用户分配查看价格(事务代码:ME23N)
    【SSH网上商城项目实战15】线程、定时器同步首页数据(类似于博客定期更新排名)
    【SSH网上商城项目实战14】商城首页UI的设计
    【SSH网上商城项目实战13】Struts2实现文件上传功能
    【SSH网上商城项目实战12】添加和更新商品功能的实现
    【SSH网上商城项目实战11】查询和删除商品功能的实现
    【SSH网上商城项目实战10】商品类基本模块的搭建
  • 原文地址:https://www.cnblogs.com/yanguobin/p/11699905.html
Copyright © 2011-2022 走看看