实现mybatis与spring进行整合,通过spring管理SqlSessionFactory、mapper接口。
tips:mybatis官方提供与mybatis与spring整合jar包。
一、Mybatis配置文件:SqlMapConfig.xml
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE configuration 3 PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 4 "http://mybatis.org/dtd/mybatis-3-config.dtd"> 5 <configuration> 6 7 <!—使用自动扫描器时,mapper.xml文件如果和mapper.java接口在一个目录则此处不用定义mappers --> 8 <mappers> 9 <package name="cn.itcast.mybatis.mapper" /> 10 </mappers> 11 </configuration>
二、Spring配置文件:在classpath下创建applicationContext.xml,定义数据库链接池、SqlSessionFactory。
1 <beans xmlns="http://www.springframework.org/schema/beans" 2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" 3 xmlns:context="http://www.springframework.org/schema/context" 4 xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 5 xsi:schemaLocation="http://www.springframework.org/schema/beans 6 http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 7 http://www.springframework.org/schema/mvc 8 http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 9 http://www.springframework.org/schema/context 10 http://www.springframework.org/schema/context/spring-context-3.2.xsd 11 http://www.springframework.org/schema/aop 12 http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 13 http://www.springframework.org/schema/tx 14 http://www.springframework.org/schema/tx/spring-tx-3.2.xsd "> 15 <!-- 加载配置文件 --> 16 <context:property-placeholder location="classpath:db.properties"/> 17 <!-- 数据库连接池 --> 18 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> 19 <property name="driverClassName" value="${jdbc.driver}"/> 20 <property name="url" value="${jdbc.url}"/> 21 <property name="username" value="${jdbc.username}"/> 22 <property name="password" value="${jdbc.password}"/> 23 <property name="maxActive" value="10"/> 24 <property name="maxIdle" value="5"/> 25 </bean> 26 <!-- mapper配置 --> 27 <!-- 让spring管理sqlsessionfactory 使用mybatis和spring整合包中的 --> 28 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> 29 <!-- 数据库连接池 --> 30 <property name="dataSource" ref="dataSource" /> 31 <!-- 加载mybatis的全局配置文件 --> 32 <property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml" /> 33 </bean> 34 35 </beans>
三、Mapper的编写
使用mapper扫描器:此方法即mapper接口开发方法,只需定义mapper接口,不用编写mapper接口实现类。只需要在spring配置文件中定义一个mapper扫描器,自动扫描包中的mapper接口生成代理对象。
1、 mapper.xml文件编写
2、定义mapper接口(注意mapper.xml的文件名和mapper的接口名称保持一致,且放在同一个目录)
3、配置mapper扫描器
1 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> 2 <property name="basePackage" value="mapper接口包地址"></property> 3 <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> 4 </bean> 5 <!-- 6 basePackage:扫描包路径,中间可以用逗号或分号分隔定义多个包 7 -->
4、使用扫描器后从spring容器中获取mapper的实现对象
tips:如果将mapper.xml和mapper接口的名称保持一致且放在一个目录 则不用在sqlMapConfig.xml中进行配置。