springmvc和mybatis整合
spring将各层进行整合
1、spring管理持久层的mapper(相当于dao接口)
mybatis和spring整合,通过spring管理mapper接口。
使用mapper的扫描器自动扫描mapper接口在spring中进行注册。
2、spring管理业务层service,service中可以调用mapper接口。
spring进行事务控制。
3、spring管理表现层Handler,Handler中可以调用service接口。
mapper、service、Handler都是javabean。
一、mybatis和spring进行整合
1、mybatis配置文件
<?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> </configuration>
2、applicationContext-dao.xml:数据源,SqlSessionFactory,mapper扫描
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<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:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 数据源 SqlSessionFactory mapper扫描器 --> <!-- 1、引入数据库连接属性文件 --> <context:property-placeholder location="classpath:jdbc.properties" /> <!-- 2、配置C3P0连接池 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${jdbc.driverClass}" /> <property name="jdbcUrl" value="${jdbc.url}" /> <property name="user" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </bean> <!-- 3、spring创建sqlSessionFactory对象 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 加载mybatis的配置文件 --> <property name="configLocation" value="mybatis/SqlMapConfig.xml" /> <!-- 数据源 --> <property name="dataSource" ref="dataSource" /> </bean> <!-- 通过MapperScannerConfigurer进行mapper扫描 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 指定扫描的包名 扫描多个包,使用半角逗号隔开 --> <property name="basePackage" value="com.xxx.springmvc.mapper"/> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> </bean> </beans>
3、mapper
3.1、mapper.java
public interface ItemsMapperCustom { //商品查询列表 public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo)throws Exception;
3.2、mapper.xml
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace="com.xxx.springmvc.mapper.ItemsMapperCustom" > <!-- 定义商品查询的sql片段,就是商品查询条件 --> <sql id="query_items_where"> <!-- 使用动态sql,通过if判断,满足条件进行sql拼接 --> <!-- 商品查询条件通过ItemsQueryVo包装对象 中itemsCustom属性传递 --> <if test="itemsCustom!=null"> <if test="itemsCustom.name!=null and itemsCustom.name!=''"> items.name LIKE '%${itemsCustom.name}%' </if> </if> </sql> <!-- 商品列表查询 --> <!-- parameterType传入包装对象(包装了查询条件) resultType建议使用扩展对象 --> <select id="findItemsList" parameterType="com.xxx.springmvc.po.ItemsQueryVo" resultType="com.xxx.springmvc.po.ItemsCustom"> SELECT items.* FROM items <where> <include refid="query_items_where"></include> </where> </select> </mapper>
二、spring管理service层
1、定义service
public class ItemsServiceImpl implements ItemsService{ @Autowired private ItemsMapperCustom itemsMapperCustom; @Override public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo) throws Exception { //通过ItemsMapperCustom查询数据库 return itemsMapperCustom.findItemsList(itemsQueryVo); }
2、spring配置(applicationContext-service.xml)
2.1、spring中管理service
<bean id="itemsService" class="com.xxx.springmvc.service.impl.ItemsServiceImpl"/>
三、事务控制(applicationContext-transaction.xml)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<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 https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 事务管理器 对mybatis操作数据库事务控制,spring使用jdbc的事务控制类 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!-- 数据源 dataSource在applicationContext-dao.xml中配置了 --> <property name="dataSource" ref="dataSource"/> </bean> <!-- 通知 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <!-- 传播行为 REQUIRED:默认值,如果方法中有事务,使用方法中的事务,如果没有事务,创建一个新事务。 SUPPORTS:支持事务,如果方法中有事务,使用方法中的事务。如果没有,不使用事务 --> <tx:method name="save*" propagation="REQUIRED"/> <tx:method name="delete*" propagation="REQUIRED"/> <tx:method name="insert*" propagation="REQUIRED"/> <tx:method name="update*" propagation="REQUIRED"/> <tx:method name="find*" propagation="SUPPORTS" read-only="true"/> <tx:method name="get*" propagation="SUPPORTS" read-only="true"/> <tx:method name="select*" propagation="SUPPORTS" read-only="true"/> </tx:attributes> </tx:advice> <!-- aop --> <aop:config> <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.xxx.spring.service.impl.*.*(..))"/> </aop:config> </beans>
四、整合springmvc
1、springmvc.xml
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<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:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <context:component-scan base-package="com.xxx.springmvc.controller"></context:component-scan> <mvc:annotation-driven></mvc:annotation-driven> <!-- 视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"></property> <property name="suffix" value=".jsp"></property> </bean> </beans>
2、配置前端控制器(DispatcherServlet)web.xml
<!-- springmvc前端控制器 --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <!-- contextConfigLocation:配置springmvc要加载的组件(处理器映射器、处理器适配器、视图解析器。。。) contextConfigLocation:默认加载路径:/WEB-INF/servlet-name-servlet.xml(springmvc-servlet.xml) --> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <!-- *.action:访问以。action结尾的由DispatcherServlet解析 /:所有访问地址都由DispatcherServlet解析,对于静态文件的解析需要配置不让DispatcherServlet解析,测试方式可以实现RESTful风格url --> <url-pattern>*.action</url-pattern> </servlet-mapping>
五、编写Controller,编写jsp(参照上一章)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
@Controller // 为了对url进行分类管理 ,可以在这里定义根路径,最终访问url是根路径+子路径 // 比如:商品列表:/items/queryItems.action @RequestMapping("/items") public class ItemsController { @Autowired private ItemsService itemsService; // 商品查询 @RequestMapping("/queryItems") public ModelAndView queryItems(HttpServletRequest request, ItemsQueryVo itemsQueryVo) throws Exception { // 测试forward后request是否可以共享 System.out.println(request.getParameter("id")); // 调用service查找 数据库,查询商品列表 List<ItemsCustom> itemsList = itemsService.findItemsList(itemsQueryVo); // 返回ModelAndView ModelAndView modelAndView = new ModelAndView(); // 相当 于request的setAttribut,在jsp页面中通过itemsList取数据 modelAndView.addObject("itemsList", itemsList); // 指定视图 // 下边的路径,如果在视图解析器中配置jsp路径的前缀和jsp路径的后缀,修改为 // modelAndView.setViewName("/WEB-INF/jsp/items/itemsList.jsp"); // 上边的路径配置可以不在程序中指定jsp路径的前缀和jsp路径的后缀 modelAndView.setViewName("items/itemsList"); return modelAndView; }
六、加载spring配置文件(建议使用通配符加载上边的配置文件),web.xml
<!-- 加载spring容器 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/classes/spring/applicationContext-*.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
最后将web.xml整体代码
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!-- 加载spring容器 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/classes/spring/applicationContext-*.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- springmvc前端控制器 --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- contextConfigLocation配置springmvc加载的配置文件(配置处理器映射器、适配器等等) 如果不配置contextConfigLocation,默认加载的是/WEB-INF/servlet名称-serlvet.xml(springmvc-servlet.xml) --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/springmvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <!-- 第一种:*.action,访问以.action结尾 由DispatcherServlet进行解析 第二种:/,所以访问的地址都由DispatcherServlet进行解析,对于静态文件的解析需要配置不让DispatcherServlet进行解析 使用此种方式可以实现 RESTful风格的url 第三种:/*,这样配置不对,使用这种配置,最终要转发到一个jsp页面时, 仍然会由DispatcherServlet解析jsp地址,不能根据jsp页面找到handler,会报错。 --> <url-pattern>*.action</url-pattern> </servlet-mapping> <!-- springmvc前端控制器,rest配置 --> <servlet> <servlet-name>springmvc_rest</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- contextConfigLocation配置springmvc加载的配置文件(配置处理器映射器、适配器等等) 如果不配置contextConfigLocation,默认加载的是/WEB-INF/servlet名称-serlvet.xml(springmvc-servlet.xml) --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/springmvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springmvc_rest</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- post乱码过虑器 --> <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>