spring和mybatis整合

来源:互联网 发布:东京八分钟知乎 编辑:程序博客网 时间:2024/06/05 15:41
  1. 01-启动spring

    在web中启动Spring,在web.xml里加入一个监听器

    spring的监听,用于启动spring

        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener </listener-class>
        </listener>
    spring配置文件默认是applicationContext.xml,默认路径是WEB-INF/里,
applicationContext.xml内容:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
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-4.1.xsd  
http://www.springframework.org/schema/context  
http://www.springframework.org/schema/context/spring-context-4.1.xsd  
http://www.springframework.org/schema/tx  
http://www.springframework.org/schema/tx/spring-tx-4.1.xsd  
http://www.springframework.org/schema/aop   
http://www.springframework.org/schema/aop/spring-aop-4.1.xsd">
</beans>


更改spring配置文件的默认位置
           <context-param> 
   <param-name>contextConfigLocation</param-name> 
   <param-value>classpath:spring.xml</param-value> 
  </context-param>

02-spring和mybatis整合

导入连库jar包
用spring容器来管理数据源(连库设置)
oracle:
<beanid="dataSource"class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<propertyname="driverClassName">
<value>oracle.jdbc.driver.OracleDriver</value>
</property>
<propertyname="url">
<value>jdbc:oracle:thin:@localhost:1521:*****</value>
</property>
<propertyname="username">
<value>mrmf</value>
</property>
<propertyname="password">
<value>mrmf</value>
</property>
</bean>

mysql:
<beanid="dataSource"class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<propertyname="driverClassName">
<value>com.mysql.jdbc.Driver</value>
</property>
<propertyname="url">
<value>jdbc:mysql://localhost:3306/springmvctest?useUnicode=true&amp;characterEncoding=utf-8</value>
</property>
<propertyname="username">
<value>root</value>
</property>
<propertyname="password">
<value>root</value>
</property>
</bean>
这里生成实体类和映射文件以及mapper
统一加载sql映射文件
    <beanid="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean">
         <propertyname="dataSource"ref="dataSource"/>
     <!-- mapper和resultmap配置路径 -->
     <propertyname="mapperLocations">
     <list>
     <value>classpath:com/turing/*/entity/*Mapper.xml</value>
      </list>
     </property>     
     </bean>
<!-- 启动spring注解功能 -->
<context:annotation-config></context:annotation-config>
统一加载mapper接口
<beanclass="org.mybatis.spring.mapper.MapperScannerConfigurer">
     <propertyname="basePackage"value="com.turing.*.mapper"/>
     </bean>
<context:annotation-config></context:annotation-config>