SpringMVC与MyBatis整合方法

一、springmvc+mybaits的系统架构:

第一步:整合dao层

         mybatis和spring整合,通过spring管理mapper接口。

         使用mapper的扫描器自动扫描mapper接口在spring中进行注册。

第二步:整合service层

         通过spring管理 service接口。

         使用配置方式将service接口配置在spring配置文件中。

         实现事务控制。

第三步:整合springmvc

         由于springmvc是spring的模块,不需要整合。

 整合步骤:

一、首先创建Mybatis自己的配置文件(例如:sqlMapConfig.xml)

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    
    <!-- 全局setting配置,根据需要添加 -->
    
    <!-- 配置别名 -->
    <typeAliases>
        <!-- 批量扫描别名 -->
        <package name="cn.itcast.ssm.po"/>
    </typeAliases>

    <!-- 配置mapper
    由于使用spring和mybatis的整合包进行mapper扫描,这里不需要配置了。
    必须遵循:mapper.xml和mapper.java文件同名且在一个目录 
     -->

    <!-- <mappers>
    
    </mappers> -->
</configuration>
View Code

 tips:使用自动扫描器时,mapper.xml文件如果和mapper.java接口在一个目录则此处不用定义mappers.

二、创建applicationContext-dao.xml文件,用以配置数据源、事务管理,配置SqlSessionFactory、mapper扫描器。

 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     <!-- 加载db.properties文件中的内容,db.properties文件中key命名要有一定的特殊规则 -->
17     <context:property-placeholder location="classpath:db.properties" />
18     <!-- 配置数据源 ,dbcp -->
19 
20     <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
21         destroy-method="close">
22         <property name="driverClassName" value="${jdbc.driver}" />
23         <property name="url" value="${jdbc.url}" />
24         <property name="username" value="${jdbc.username}" />
25         <property name="password" value="${jdbc.password}" />
26         <property name="maxActive" value="30" />
27         <property name="maxIdle" value="5" />
28     </bean>
29     <!-- sqlSessionFactory -->
30     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
31         <!-- 数据库连接池 -->
32         <property name="dataSource" ref="dataSource" />
33         <!-- 加载mybatis的全局配置文件 -->
34         <property name="configLocation" value="classpath:mybatis/sqlMapConfig.xml" />
35     </bean>
36     <!-- mapper扫描器 -->
37     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
38         <!-- 扫描包路径,如果需要扫描多个包,中间使用半角逗号隔开 -->
39         <property name="basePackage" value="cn.itcast.ssm.mapper"></property>
40         <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
41     </bean>
42 
43 </beans>
View Code

 db.properties:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=root
jdbc.password=mysql
View Code

 tips:使用逆向工程生成po类及mapper(单表增删改查)

 三、手动定义商品查询mapper及商品查询dao接口

ItemsMapperCustom.xml

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
 3 <mapper namespace="cn.itcast.ssm.mapper.ItemsMapperCustom" >
 4 
 5    <!-- 定义商品查询的sql片段,就是商品查询条件 -->
 6    <sql id="query_items_where">
 7        <!-- 使用动态sql,通过if判断,满足条件进行sql拼接 -->
 8        <!-- 商品查询条件通过ItemsQueryVo包装对象 中itemsCustom属性传递 -->
 9            <if test="itemsCustom!=null">
10                <if test="itemsCustom.name!=null and itemsCustom.name!=''">
11                    items.name LIKE '%${itemsCustom.name}%'
12                </if>
13            </if>
14     
15    </sql>
16       
17       <!-- 商品列表查询 -->
18       <!-- parameterType传入包装对象(包装了查询条件)
19           resultType建议使用扩展对象
20        -->
21       <select id="findItemsList" parameterType="cn.itcast.ssm.po.ItemsQueryVo"
22            resultType="cn.itcast.ssm.po.ItemsCustom">
23           SELECT items.* FROM items  
24           <where>
25               <include refid="query_items_where"></include>
26           </where>
27       </select>
28       
29 </mapper
View Code

 ItemsMapperCustom.java

 1 package cn.itcast.ssm.mapper;
 2 
 3 import cn.itcast.ssm.po.Items;
 4 import cn.itcast.ssm.po.ItemsCustom;
 5 import cn.itcast.ssm.po.ItemsExample;
 6 import cn.itcast.ssm.po.ItemsQueryVo;
 7 
 8 import java.util.List;
 9 import org.apache.ibatis.annotations.Param;
10 
11 public interface ItemsMapperCustom {
12     //商品查询列表
13     public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo)throws Exception;
14 }
View Code

四、整合service,让spring管理service接口,进行事务管理配置。

首先,定义Service接口和Service的实现类

 1 package cn.itcast.ssm.service;
 2 
 3 import java.util.List;
 4 
 5 import cn.itcast.ssm.po.ItemsCustom;
 6 import cn.itcast.ssm.po.ItemsQueryVo;
 7 
 8 /**
 9  * 
10  * <p>Title: ItemsService</p>
11  * <p>Description:商品管理service </p>
12  * <p>Company: www.itcast.com</p> 
13  * @author    传智.燕青
14  * @date    2015-4-13下午3:48:09
15  * @version 1.0
16  */
17 public interface ItemsService {
18     
19     //商品查询列表
20     public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo) throws Exception;
21     
22     //根据id查询商品信息
23     /**
24      * 
25      * <p>Title: findItemsById</p>
26      * <p>Description: </p>
27      * @param id 查询商品的id
28      * @return
29      * @throws Exception
30      */
31     public ItemsCustom findItemsById(Integer id) throws Exception;
32     
33     //修改商品信息
34     /**
35      * 
36      * <p>Title: updateItems</p>
37      * <p>Description: </p>
38      * @param id 修改商品的id
39      * @param itemsCustom 修改的商品信息
40      * @throws Exception
41      */
42     public void updateItems(Integer id,ItemsCustom itemsCustom) throws Exception;
43     
44 
45 }
View Code 
 1 package cn.itcast.ssm.service.impl;
 2 
 3 import java.util.List;
 4 
 5 import org.springframework.beans.BeanUtils;
 6 import org.springframework.beans.factory.annotation.Autowired;
 7 
 8 import cn.itcast.ssm.mapper.ItemsMapper;
 9 import cn.itcast.ssm.mapper.ItemsMapperCustom;
10 import cn.itcast.ssm.po.Items;
11 import cn.itcast.ssm.po.ItemsCustom;
12 import cn.itcast.ssm.po.ItemsQueryVo;
13 import cn.itcast.ssm.service.ItemsService;
14 
15 /**
16  * 
17  * <p>Title: ItemsServiceImpl</p>
18  * <p>Description: 商品管理</p>
19  * <p>Company: www.itcast.com</p> 
20  * @author    传智.燕青
21  * @date    2015-4-13下午3:49:54
22  * @version 1.0
23  */
24 public class ItemsServiceImpl implements ItemsService{
25     
26     @Autowired
27     private ItemsMapperCustom itemsMapperCustom;
28     
29     @Autowired
30     private ItemsMapper itemsMapper;
31 
32     @Override
33     public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo)
34             throws Exception {
35         //通过ItemsMapperCustom查询数据库
36         return itemsMapperCustom.findItemsList(itemsQueryVo);
37     }
38 
39     @Override
40     public ItemsCustom findItemsById(Integer id) throws Exception {
41         
42         Items items = itemsMapper.selectByPrimaryKey(id);
43         //中间对商品信息进行业务处理
44         //....
45         //返回ItemsCustom
46         ItemsCustom itemsCustom = new ItemsCustom();
47         //将items的属性值拷贝到itemsCustom
48         BeanUtils.copyProperties(items, itemsCustom);
49         
50         return itemsCustom;
51         
52     }
53 
54     @Override
55     public void updateItems(Integer id, ItemsCustom itemsCustom) throws Exception {
56         //添加业务校验,通常在service接口对关键参数进行校验
57         //校验 id是否为空,如果为空抛出异常
58         
59         //更新商品信息使用updateByPrimaryKeyWithBLOBs根据id更新items表中所有字段,包括 大文本类型字段
60         //updateByPrimaryKeyWithBLOBs要求必须转入id
61         itemsCustom.setId(id);
62         itemsMapper.updateByPrimaryKeyWithBLOBs(itemsCustom);
63     }
64 
65 }
View Code

然后,在spring容器配置service(applicationContext-service.xml)

1 <bean id="itemsService" class="cn.itcast.ssm.service.impl.ItemsServiceImpl"/>
2 </beans>
View Code

配置事务控制,applicationContext-transcation.xml

 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 <!-- 事务管理器 
17     对mybatis操作数据库事务控制,spring使用jdbc的事务控制类
18 -->
19 <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
20     <!-- 数据源
21     dataSource在applicationContext-dao.xml中配置了
22      -->
23     <property name="dataSource" ref="dataSource"/>
24 </bean>
25 
26 <!-- 通知 -->
27 <tx:advice id="txAdvice" transaction-manager="transactionManager">
28     <tx:attributes>
29         <!-- 传播行为 -->
30         <tx:method name="save*" propagation="REQUIRED"/>
31         <tx:method name="delete*" propagation="REQUIRED"/>
32         <tx:method name="insert*" propagation="REQUIRED"/>
33         <tx:method name="update*" propagation="REQUIRED"/>
34         <tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
35         <tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
36         <tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
37     </tx:attributes>
38 </tx:advice>
39 <!-- aop -->
40 <aop:config>
41     <aop:advisor advice-ref="txAdvice" pointcut="execution(* cn.itcast.ssm.service.impl.*.*(..))"/>
42 </aop:config>
43 
44 </beans>
View Code 

五、配置springmvc.xml文件

 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     <!-- 可以扫描controller、service、...
17     这里让扫描controller,指定controller的包
18      -->
19     <context:component-scan base-package="cn.itcast.ssm.controller"></context:component-scan>
20     
21         
22     <!--注解映射器 -->
23     <!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/> -->
24     <!--注解适配器 -->
25     <!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/> -->
26     
27     <!-- 使用 mvc:annotation-driven代替上边注解映射器和注解适配器配置
28     mvc:annotation-driven默认加载很多的参数绑定方法,
29     比如json转换解析器就默认加载了,如果使用mvc:annotation-driven不用配置上边的RequestMappingHandlerMapping和RequestMappingHandlerAdapter
30     实际开发时使用mvc:annotation-driven
31      -->
32     <mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
33     
34 
35     <!-- 视图解析器
36     解析jsp解析,默认使用jstl标签,classpath下的得有jstl的包
37      -->
38     <bean
39         class="org.springframework.web.servlet.view.InternalResourceViewResolver">
40         <!-- 配置jsp路径的前缀 -->
41         <property name="prefix" value="/WEB-INF/jsp/"/>
42         <!-- 配置jsp路径的后缀 -->
43         <property name="suffix" value=".jsp"/>
44     </bean>
45     
46     <!-- 自定义参数绑定 -->
47     <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
48         <!-- 转换器 -->
49         <property name="converters">
50             <list>
51                 <!-- 日期类型转换 -->
52                 <bean class="cn.itcast.ssm.controller.converter.CustomDateConverter"/>
53             </list>
54         </property>
55         
56     
57     </bean>
58 </beans>
View Code

六、编写controller

 1 @RequestMapping("/items")
 2 public class ItemsController {
 3 
 4     @Autowired
 5     private ItemsService itemsService;
 6 
 7     // 商品查询
 8     @RequestMapping("/queryItems")
 9     public ModelAndView queryItems(HttpServletRequest request) throws Exception {
10         //测试forward后request是否可以共享
11         
12         System.out.println(request.getParameter("id"));
13 
14         // 调用service查找 数据库,查询商品列表
15         List<ItemsCustom> itemsList = itemsService.findItemsList(null);
16         
17         // 返回ModelAndView
18         ModelAndView modelAndView = new ModelAndView();
19         // 相当 于request的setAttribut,在jsp页面中通过itemsList取数据
20         modelAndView.addObject("itemsList", itemsList);
21 
22         // 指定视图
23         // 下边的路径,如果在视图解析器中配置jsp路径的前缀和jsp路径的后缀,修改为
24         // modelAndView.setViewName("/WEB-INF/jsp/items/itemsList.jsp");
25         // 上边的路径配置可以不在程序中指定jsp路径的前缀和jsp路径的后缀
26         modelAndView.setViewName("items/itemsList");
27 
28         return modelAndView;
29 
30     }
31 }
View Code

七、编写JSP页面(省略...)

八、加载spring容器

在web.xml文件中进行如下配置

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 3     xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 4     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 5     id="WebApp_ID" version="2.5">
 6     <display-name>springmvc_mybatis1208</display-name>
 7 
 8     <!-- 加载spring容器 -->
 9     <context-param>
10         <param-name>contextConfigLocation</param-name>
11         <param-value>/WEB-INF/classes/spring/applicationContext-*.xml</param-value>
12     </context-param>
13     <listener>
14         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
15     </listener>
16 
17 
18     <!-- springmvc前端控制器 -->
19     <servlet>
20         <servlet-name>springmvc</servlet-name>
21         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
22         <!-- contextConfigLocation配置springmvc加载的配置文件(配置处理器映射器、适配器等等) 如果不配置contextConfigLocation,默认加载的是/WEB-INF/servlet名称-serlvet.xml(springmvc-servlet.xml) -->
23         <init-param>
24             <param-name>contextConfigLocation</param-name>
25             <param-value>classpath:spring/springmvc.xml</param-value>
26         </init-param>
27     </servlet>
28 
29     <servlet-mapping>
30         <servlet-name>springmvc</servlet-name>
31         <!-- 第一种:*.action,访问以.action结尾 由DispatcherServlet进行解析 第二种:/,所以访问的地址都由DispatcherServlet进行解析,对于静态文件的解析需要配置不让DispatcherServlet进行解析 
32             使用此种方式可以实现 RESTful风格的url 第三种:/*,这样配置不对,使用这种配置,最终要转发到一个jsp页面时, 仍然会由DispatcherServlet解析jsp地址,不能根据jsp页面找到handler,会报错。 -->
33         <url-pattern>*.action</url-pattern>
34     </servlet-mapping>
35 
36     <!-- post乱码过虑器 -->
37     <filter>
38         <filter-name>CharacterEncodingFilter</filter-name>
39         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
40         <init-param>
41             <param-name>encoding</param-name>
42             <param-value>utf-8</param-value>
43         </init-param>
44     </filter>
45     <filter-mapping>
46         <filter-name>CharacterEncodingFilter</filter-name>
47         <url-pattern>/*</url-pattern>
48     </filter-mapping>
49 
50     <welcome-file-list>
51         <welcome-file>index.html</welcome-file>
52         <welcome-file>index.htm</welcome-file>
53         <welcome-file>index.jsp</welcome-file>
54         <welcome-file>default.html</welcome-file>
55         <welcome-file>default.htm</welcome-file>
56         <welcome-file>default.jsp</welcome-file>
57     </welcome-file-list>
58 </web-app>
View Code
原文地址:https://www.cnblogs.com/ustc-anmin/p/10463025.html