17.spring和mybatis整合

github地址:https://github.com/Ching-Lee/spring_mybatis

1.整合思路

需要spring通过单例方式管理SqlSessionFactory。
spring和mybatis整合生成代理对象,使用SqlSessionFactory创建SqlSession。(spring和mybatis整合自动完成)
持久层的mapper都需要由spring进行管理。

2.整合环境

创建一个新的java工程(接近实际开发的工程结构)

  • jar包:

    mybatis3.2.7的jar包
    spring4.3.12的jar包
    mybatis和spring的整合包:由mybatis提供
    注意:jdk1.8版本必须使用spring4._的包,不然会出错。



    加入到工程中:


  • config配置文件

新建config根目录文件夹,添加文件,新建包,工程结构最终如下所示

  • sqlSessionFactory

在applicationContext.xml配置sqlSessionFactory和数据源。

<?xml version="1.0"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-3.2.xsd
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
            http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">

    <!--加载数据库的配置文件-->
    <context:property-placeholder location="classpath:db.properties"/>
    <!--数据源,使用dhcp-->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="maxActive" value="10"/>
        <property name="maxIdle" value="5"/>
    </bean>

    <!-- sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 加载mybatis配置文件-->
        <property name="configLocation" value="mybatis/SqlMapConfig.xml"/>
        <!--数据源-->
        <property name="dataSource" ref="dataSource"/>
    </bean>



</beans>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容