一、簡單測試工程搭建
1、Mybatis所需要的的jar包(包含數據庫驅動包和相關的日志包)、SpringMVC和Spring的jar包

2、然后構建一個基本的工程,這里我們使用mapper代理的方式進行Mybatis的編寫,關於mapper代理請參考Mybatis簡單入門中的Mybatis開發dao方法簡介中講到的mapper代理方式,所以在項目中我們不建立dao包,需要建立mapper包用來存放mapper接口和相應的mapper配置文件。

二、配置Mybatis和Spring整合
1、配置Mybatis的核心配置文件,因為是和Spring整合,所以數據庫的配置交給Spring管理由Spring進行數據源的配置。
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 <typeAliases> 8 <!--批量別名定義:Mybatis在定義別名的時候會自動掃描包中的po類,自動的將別名定義為類名(首字母大寫或者小寫都可以)--> 9 <package name="cn.test.ssm.mapper"></package> 10 </typeAliases> 11 12 </configuration>
2、下來是Spring和Mybatis的整合,可以參考前面的Mybatis和Spring整合篇中的mapper代理方式。到這里我們就需要配置Spring整合Mybatis的配置文件了,在Spring和Mybatis的整合文件applicationContext-dao.xml配置文件中我們需要配置數據源(dataSource)、會話工廠(sqlSessionFactory)和Mapper掃描器
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:aop="http://www.springframework.org/schema/aop" 6 xmlns:tx="http://www.springframework.org/schema/tx" 7 xsi:schemaLocation=" 8 http://www.springframework.org/schema/beans 9 http://www.springframework.org/schema/beans/spring-beans.xsd 10 http://www.springframework.org/schema/aop 11 http://www.springframework.org/schema/aop/spring-aop.xsd 12 http://www.springframework.org/schema/context 13 http://www.springframework.org/schema/context/spring-context.xsd 14 http://www.springframework.org/schema/tx 15 http://www.springframework.org/schema/tx/spring-tx.xsd"> 16 17 18 <!--加載數據庫信息的配置文件--> 19 <context:property-placeholder location="classpath:db.properties"></context:property-placeholder> 20 21 <!--配置數據源--> 22 <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> 23 <property name="driverClass" value="${jdbc.driver}" /> 24 <property name="jdbcUrl" value="${jdbc.url}" /> 25 <property name="user" value="${jdbc.username}" /> 26 <property name="password" value="${jdbc.password}" /> 27 </bean> 28 29 <!--配置SqlSessionFactory--> 30 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> 31 <!--加載Mybatis的配置文件--> 32 <property name="configLocation" value="classpath:mybatis/sqlMapConfig.xml"></property> 33 <!--配置數據源--> 34 <property name="dataSource" ref="dataSource"></property> 35 </bean> 36 37 <!--配置mapper掃描器--> 38 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> 39 <property name="basePackage" value="cn.test.ssm.mapper"></property> 40 <property name="sqlSessionTemplateBeanName" value="sqlSessionFactory"></property> 41 </bean> 42 </beans>
3、接下來我們就開始編寫一個簡單測mapper測試配置文件,只完成一個小功能(查詢一個列表集合) ,在里面使用一些簡單的動態sql進行判斷避免異常
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE mapper 3 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 4 "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 5 <!--mapper為根元素,namespace指定了命名空間--> 6 <mapper namespace="cn.test.ssm.mapper.ProductDemo"> 7 8 <!--實現一個簡單的列表查詢的功能(使用動態sql和sql片段便於擴展,雖然這只是個小的demo並沒有做其他的擴展,但是可以養成一種習慣)--> 9 10 <!--sql片段+動態sql--> 11 <sql id="queryListCondition"> 12 <where> 13 <if test="productExtend != null"> 14 <if test="productExtend.name != null and productExtend.name != ''"> 15 product.pname LIKE '%${productExtend.name}%' 16 </if> 17 </if> 18 </where> 19 </sql> 20 21 <!--為了便於擴展,使用ProductExtent類作為輸出映射,這樣除了可以查詢Product之外還可以擴展其他的字段--> 22 <select id="findProductListByName" parameterType="cn.test.ssm.po.ProductQueryVo" resultType="cn.test.ssm.po.ProductExtend"> 23 SELECT product.* FROM product 24 <where> 25 <include refid="queryListCondition"></include> 26 </where> 27 </select> 28 </mapper>
4、寫完mapper配置文件之后就寫一個接單的接口程序,其中只包含一個方法就是查詢列表信息。
1 package cn.test.ssm.mapper; 2 3 import cn.test.ssm.po.ProductExtend; 4 import cn.test.ssm.po.ProductQueryVo; 5 6 import java.util.List; 7 8 public interface ProductDemo { 9 10 public List<ProductExtend> findProductListByName(ProductQueryVo productQueryVo) throws Exception; 11 }
三、配置Spring和Service層整合
1、一般情況下都是定義service接口和對應的實現類,這里我們也定義一個簡單的ProductService接口和其實現類作為service層的主要類
①Product Service接口:主要就是要調用mapper接口中定義的那一個查詢列表的方法
1 package cn.test.ssm.service; 2 3 import cn.test.ssm.po.ProductExtend; 4 import cn.test.ssm.po.ProductQueryVo; 5 6 import java.util.List; 7 8 public interface ProductService { 9 public List<ProductExtend> findProductListByName(ProductQueryVo productQueryVo) throws Exception; 10 }
②ProductServiceImpl實現類,實現上面接口中的方法,由於要和Mybatis和Spring已經整合(采用mapper代理的方式),並且在applicationContext-dao配置文件中配置了mapper掃描器,所以我們可以使用注解的方式注入Mapper接口然后在service中調用接口中的方法
1 package cn.test.ssm.service.impl; 2 3 import cn.test.ssm.mapper.ProductDemo; 4 import cn.test.ssm.po.ProductExtend; 5 import cn.test.ssm.po.ProductQueryVo; 6 import cn.test.ssm.service.ProductService; 7 import org.springframework.beans.factory.annotation.Autowired; 8 9 import java.util.List; 10 11 public class ProductServiceImpl implements ProductService { 12 13 @Autowired 14 private ProductDemo productDemo; //自動注入mapper接口,然后在實現service的方法中調用mapper接口中的方法 15 16 @Override 17 public List<ProductExtend> findProductListByName(ProductQueryVo productQueryVo) throws Exception { 18 return productDemo.findProductListByName(productQueryVo); 19 } 20 }
2、上面寫好了接口和實現類,然后就是將service交給Spring進行管理,配置applicationContext-service.xml對service進行整合。對service整合主要包括:service本身接口實現類的bean配置、事務控制等
①管理service本身的接口實現類的bean
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:aop="http://www.springframework.org/schema/aop" 6 xmlns:tx="http://www.springframework.org/schema/tx" 7 xsi:schemaLocation=" 8 http://www.springframework.org/schema/beans 9 http://www.springframework.org/schema/beans/spring-beans.xsd 10 http://www.springframework.org/schema/aop 11 http://www.springframework.org/schema/aop/spring-aop.xsd 12 http://www.springframework.org/schema/context 13 http://www.springframework.org/schema/context/spring-context.xsd 14 http://www.springframework.org/schema/tx 15 http://www.springframework.org/schema/tx/spring-tx.xsd"> 16 17 <!--對service本身的接口實現類的bean配置--> 18 <bean id="productService" class="cn.test.ssm.service.impl.ProductServiceImpl"> 19 20 </bean> 21 22 </beans>
②進行事務控制的配置
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:aop="http://www.springframework.org/schema/aop" 6 xmlns:tx="http://www.springframework.org/schema/tx" 7 xsi:schemaLocation=" 8 http://www.springframework.org/schema/beans 9 http://www.springframework.org/schema/beans/spring-beans.xsd 10 http://www.springframework.org/schema/aop 11 http://www.springframework.org/schema/aop/spring-aop.xsd 12 http://www.springframework.org/schema/context 13 http://www.springframework.org/schema/context/spring-context.xsd 14 http://www.springframework.org/schema/tx 15 http://www.springframework.org/schema/tx/spring-tx.xsd"> 16 17 <!-- 18 事務控制的配置 19 對數據庫操作Mybatis的事務控制使用spring的jdbc事務管理控制類 20 --> 21 22 <!--事務管理器--> 23 <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 24 <!--添加對數據源的控制--> 25 <property name="dataSource" ref="dataSource"></property> 26 </bean> 27 28 <!--通知--> 29 <tx:advice id="txAdvice"> 30 <tx:attributes> 31 <!--配置傳播行為--> 32 <!--配置必須進行事務控制的方法--> 33 <tx:method name="save*" propagation="REQUIRED"/> 34 <tx:method name="delete*" propagation="REQUIRED"></tx:method> 35 <tx:method name="insert*" propagation="REQUIRED"></tx:method> 36 <tx:method name="update*" propagation="REQUIRED"></tx:method> 37 <!--配置支持事務的方法--> 38 <tx:method name="find*" propagation="SUPPORTS" read-only="true"></tx:method> 39 </tx:attributes> 40 </tx:advice> 41 42 <!--配置aop去調用通知--> 43 <aop:config> 44 <aop:advisor advice-ref="txAdvice" pointcut="execution(* cn.test.ssm.service.impl.*.*(..))"></aop:advisor> 45 </aop:config> 46 </beans>
四、配置整合springmvc和spring
1、首先配置springmvc的配置文件,其中包括處理器映射器、處理器適配器、視圖解析器的配置和對controller層包自動掃描的配置
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 6 xsi:schemaLocation="http://www.springframework.org/schema/beans 7 http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 8 http://www.springframework.org/schema/mvc 9 http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 10 http://www.springframework.org/schema/context 11 http://www.springframework.org/schema/context/spring-context-3.2.xsd 12 http://www.springframework.org/schema/aop 13 http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 14 http://www.springframework.org/schema/tx 15 http://www.springframework.org/schema/tx/spring-tx-3.2.xsd "> 16 17 18 <!--配置controller的掃描--> 19 <context:component-scan base-package="cn.test.ssm.controller"></context:component-scan> 20 21 <!--配置mvc:annotation代替基於注解方式的處理器映射器和適配器的配置--> 22 <mvc:annotation-driven></mvc:annotation-driven> 23 24 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"></bean> 25 </beans>
2、下來在web.xml中配置springmvc的前端控制器,里面主要包括DispatcherServlet的配置以及springmvc配置文件的路徑配置。
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" 5 version="4.0"> 6 <!--配置前端控制器--> 7 <servlet> 8 <servlet-name>SpringMvc</servlet-name> 9 <servlet-class> 10 org.springframework.web.servlet.DispatcherServlet 11 </servlet-class> 12 <!-- 13 配飾SpringMVC的配置文件(處理器映射器、適配器等) 14 注明需要這樣配置的原因:自己配置contextConfigLocation,就不會自己默認加載/WEB-INF/下面的dispatch-servlet.xml 15 --> 16 <init-param> 17 <param-name>contextConfigLocation</param-name> 18 <param-value>classpath:spring/applicationContext-springmvc.xml</param-value> 19 </init-param> 20 </servlet> 21 <servlet-mapping> 22 <servlet-name>SpringMvc</servlet-name> 23 <url-pattern>*.do</url-pattern> 24 </servlet-mapping> 25 </web-app>
五、在controller層寫handler程序
這里實現的功能也比較簡單,由於只是為了測試整個整合流程的正確,所以依舊是按照查詢列表進行編寫,然后從service調用方法,返回模型視圖、
1 package cn.test.ssm.controller; 2 3 import cn.test.ssm.po.ProductExtend; 4 import cn.test.ssm.service.ProductService; 5 import org.springframework.beans.factory.annotation.Autowired; 6 import org.springframework.stereotype.Controller; 7 import org.springframework.web.bind.annotation.RequestMapping; 8 import org.springframework.web.servlet.ModelAndView; 9 10 import java.util.List; 11 12 @Controller 13 public class ProductController { 14 15 @Autowired 16 private ProductService productService; 17 18 @RequestMapping("/queryList.do") 19 public ModelAndView queryList() throws Exception{ 20 21 //從service層調用方法 22 List<ProductExtend> productExtendList = productService.findProductListByName(null); 23 24 //返回ModelandView 25 ModelAndView modelAndView = new ModelAndView(); 26 modelAndView.addObject(productExtendList); 27 modelAndView.setViewName("/WEB-INF/items/itemsList.jsp"); 28 29 return modelAndView; 30 } 31 }
六、配置Spring容器
到這里,我們還需要配置spring容器的監聽和相應配置文件(applicationContext-dao.xml......)的加載。在配置文件中我們需要在IDEA中修改class文件的輸出路徑(本來默認是自動建立out文件,然后將class文件輸出進去),參考這篇博客。至此,所有的配置都已經完成,下面就開始測試
1 <!--配置spring容器的監聽器--> 2 <context-param> 3 <param-name>contextConfigLocation</param-name> 4 <param-value>/WEB-INF/classes/spring/applicationContext-*.xml</param-value> 5 </context-param> 6 <listener> 7 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 8 </listener>
七、使用簡單的jsp視圖進行測試
1、數據庫中的Product表信息:
1 CREATE TABLE `product` ( 2 `pid` INT(11) NOT NULL AUTO_INCREMENT, 3 `pname` VARCHAR(255) DEFAULT NULL, 4 `shop_price` DOUBLE DEFAULT NULL, 5 PRIMARY KEY (`pid`) 6 ) ENGINE=INNODB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8

2、然后在瀏覽器中輸入http://localhost:8080/TestSSM2/queryList.do測試得到下面的結果信息

