Mybatis整合Spring

 整合思路

 

1、SqlSessionFactory对象应该放到spring容器中作为单例存在。

 

2、传统dao的开发方式中,应该从spring容器中获得sqlsession对象。

 

3、Mapper代理形式中,应该从spring容器中直接获得mapper的代理对象。

 

4、数据库的连接以及数据库连接池管理都交给spring容器来完成。

 

整合需要的jar

 

1、springjar

 

2、Mybatisjar

 

3、Spring+mybatis的整合包。

 

4、Mysql的数据库驱动jar包。

 

5、数据库连接池的jar包。(在eclipse)

 

 然后建立一个资源文件夹config

 加入配置文件

把之前的Mybatis里的config里的内容 复制到里面

 

 

 

 

然后修改sqlMapConfig.xml

 

 

 

在config创建一个applicationContext.xml

粘贴约束:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">

在复制

<!-- 加载配置文件 -->
   <context:property-placeholder location="classpath:db.properties" />

    <!-- 数据库连接池 -->
    <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="classpath:SqlMapConfig.xml" />
        <!-- 配置数据源 -->
        <property name="dataSource" ref="dataSource" />
    </bean>

数据库配置类型有两种:

一种dbcp

一种c3p0

这次我们还是用之前的Mybatis包

所以把逆向工程的里的

 

 mapper和pojo复制到src里

最后

 

 然后在

配置mapper代理

在applicationContext.xml里复制

 

<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
    <!-- 配置Mapper接口 -->
    <property name="mapperInterface" value="cn.mybatis.mapper.UserMapper" />
    <!-- 配置sqlSessionFactory -->
    <property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>

 

然后修改配置mapper接口的value

 

 

 创建测试类:

 

posted @ 2020-04-08 14:45  邢昊天  阅读(122)  评论(0)    收藏  举报