javascript
Spring+SpringMVC+MyBatis深入学习及搭建(十四)——SpringMVC和MyBatis整合
轉(zhuǎn)載請(qǐng)注明出處:http://www.cnblogs.com/Joanna-Yan/p/7010363.html?
前面講到:Spring+SpringMVC+MyBatis深入學(xué)習(xí)及搭建(十三)——SpringMVC入門(mén)程序(二)
1.需求
使用springmvc和mybatis完成商品列表查詢(xún)。
2.整合思路
springmvc+mybatis的系統(tǒng)架構(gòu):
第一步:整合dao層
mybatis和spring整合,通過(guò)spring管理mapper接口。
使用mapper的掃描器自動(dòng)掃描mapper接口在spring中進(jìn)行注冊(cè)。
第二步:整合service層
通過(guò)spring管理service接口。
使用配置方式將service接口配置在spring配置文件中。
實(shí)現(xiàn)事務(wù)控制。
第三步:整合springMvc
由于springmvc是spring的模塊,不需要整合。
3.環(huán)境準(zhǔn)備
數(shù)據(jù)庫(kù)環(huán)境:mysql5.6
java環(huán)境:
jdk1.7
MyEclipse2014
springmvc版本:spring3.2
所需要的jar包:
數(shù)據(jù)庫(kù)驅(qū)動(dòng)包
mybatis的jar包
mybatis的spring的整合包
log4j包
dbcp數(shù)據(jù)庫(kù)連接池包
spring3.2所有jar包
jstl包
過(guò)程結(jié)構(gòu)目錄:
4.整合dao
?mybatis和spring進(jìn)行整合。
4.1 db.properties
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/mybatisdemo jdbc.username=root jdbc.password=4.2 log4j.properties
# Global logging configuration,建議開(kāi)發(fā)環(huán)境要用debug log4j.rootLogger=DEBUG, stdout # Console output... log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n4.3 sqlMapConfig.xml
在classpath下創(chuàng)建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配置,根據(jù)需要添加 --><!-- 配置別名 --><typeAliases><!-- 批量掃描別名 --><package name="joanna.yan.ssm.po"/></typeAliases><!-- 配置mapper由于使用spring和mybatis的整合包進(jìn)行mapper掃描,這里不需要配置了。但是必須遵循:mapper.xml和mapper.java文件同名且在一個(gè)目錄--><!-- <mappers></mappers> --></configuration>4.4 applicationContext-dao.xml
在classpath下創(chuàng)建spring/applicationContext-dao.xml。配置:數(shù)據(jù)源、事務(wù)管理、SqlSessionFactory、mapper掃描器。
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"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-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd "><!-- 加載db.properties文件中的內(nèi)容,db.properties文件中的key命名要有一定的特殊規(guī)則 --><context:property-placeholder location="classpath:db.properties"/><!-- 配置數(shù)據(jù)源,dbcp --><bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"><property name="driverClassName" value="${jdbc.driver}"/><property name="url" value="${jdbc.url}"/><property name="username" value="${jdbc.username}"/><property name="password" value="${jdbc.password}"/><property name="maxActive" value="30"/><property name="maxIdle" value="5"/></bean><!-- sqlSessinFactory --><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><!-- 加載mybatis的全局配置文件 --><property name="configLocation" value="classpath:mybatis/sqlMapConfig.xml" /><!-- 數(shù)據(jù)庫(kù)連接池 --><property name="dataSource" ref="dataSource" /></bean><!-- mapper掃描器 --><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><!-- 掃描包路徑,如果需要掃描多個(gè)包,中間使用半角逗號(hào)隔開(kāi) --><property name="basePackage" value="joanna.yan.ssm.mapper"/><property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/></bean></beans>4.5逆向工程生成po類(lèi)及mapper(即單表增刪改查)
詳情見(jiàn):Spring+SpringMVC+MyBatis深入學(xué)習(xí)及搭建(十)——MyBatis逆向工程
將生成的文件拷貝至工程中。
4.6手動(dòng)定義商品查詢(xún)mapper
針對(duì)綜合查詢(xún)mapper,一般情況會(huì)有關(guān)聯(lián)查詢(xún),建議自定義mapper。
4.6.1 ItemsMapperCustom.xml
sql語(yǔ)句:
???????? SELECT * FROM items? WHERE items.name LIKE '%筆記本%'
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace="joanna.yan.ssm.mapper.ItemsMapperCustom" ><!-- 定義商品查詢(xún)的sql片段,就是商品查詢(xún)條件 --><sql id="query_items_where"><!-- 使用動(dòng)態(tài)sql,通過(guò)if判斷,滿(mǎn)足條件進(jìn)行sql拼接 --><!-- 商品查詢(xún)條件通過(guò)ItemsQueryVo包裝對(duì)象中itemsCustom屬性傳遞 --><if test="itemsCustom!=null"><if test="itemsCustom.name!=null and itemsCustom.name!=''">items.name LIKE '%${itemsCustom.name}%'</if></if></sql><!-- 商品列表查詢(xún) --><!-- parameterType傳入包裝對(duì)象(包裝了查詢(xún)條件)resultType建議使用擴(kuò)展對(duì)象--><select id="findItemsList" parameterType="joanna.yan.ssm.po.ItemsQueryVo" resultType="joanna.yan.ssm.po.ItemsCustom">SELECT items.* FROM items<where><include refid="query_items_where"></include></where></select> </mapper>4.6.2?ItemsMapperCustom.java
public interface ItemsMapperCustom {//商品查詢(xún)列表public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo) throws Exception; }5.整合service
讓spring管理service接口。
5.1定義service接口
package joanna.yan.ssm.service;import java.util.List; import joanna.yan.ssm.po.ItemsCustom; import joanna.yan.ssm.po.ItemsQueryVo;public interface ItemsService {//商品查詢(xún)列表public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo) throws Exception; } package joanna.yan.ssm.service.impl;import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import joanna.yan.ssm.mapper.ItemsMapperCustom; import joanna.yan.ssm.po.ItemsCustom; import joanna.yan.ssm.po.ItemsQueryVo; import joanna.yan.ssm.service.ItemsService;public class ItemsServiceImpl implements ItemsService{@Autowiredprivate ItemsMapperCustom itemsMapperCustom;@Overridepublic List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo)throws Exception {//通過(guò)ItemsMapperCustom查詢(xún)數(shù)據(jù)庫(kù)return itemsMapperCustom.findItemsList(itemsQueryVo);} }5.2在spring容器配置service(applicationContext-service.xml)
?在classpath下創(chuàng)建spring/applicationContext-service.xml,文件中配置service。
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"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-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd "><!-- 商品管理的service --><bean id="itemsService" class="joanna.yan.ssm.service.impl.ItemsServiceImpl"/></beans>5.3事務(wù)控制(applicationContext-transaction.xml)
在classpath下創(chuàng)建spring/applicationContext-service.xml,文件中使用spring聲明式事務(wù)控制方法。
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"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-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd "><!-- 事務(wù)管理器對(duì)mybatis操作數(shù)據(jù)庫(kù)事務(wù)控制,spring使用jdbc的事務(wù)控制類(lèi)--><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><!-- 數(shù)據(jù)源dataSource在applicationContext-dao.xml中配置了--><property name="dataSource" ref="dataSource"/> </bean><!-- 通知 --><tx:advice id="txAdvice" transaction-manager="transactionManager"><tx:attributes><!-- 傳播行為 --><!-- 可以變相的規(guī)范程序員的命名,例如以save開(kāi)頭,update開(kāi)頭等,不能想怎么命名就怎么命名 --><tx:method name="save*" propagation="REQUIRED"/><!-- 要求 --><tx:method name="delete*" propagation="REQUIRED"/><tx:method name="update*" propagation="REQUIRED"/><tx:method name="insert*" propagation="REQUIRED"/><tx:method name="find*" propagation="SUPPORTS" read-only="true"/> <!-- 支持,如果沒(méi)有就算了 --><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><!-- 切入點(diǎn)為joanna.yan.ssm.service.impl包下所有類(lèi)的所有方法,不管里面什么參數(shù) --><aop:advisor advice-ref="txAdvice" pointcut="execution(* joanna.yan.ssm.service.impl.*.*(..))"/></aop:config> </beans>6.整合springmvc?
6.1 springmvc.xml
在classpath下創(chuàng)建spring/springvc.xml文件,配置處理器映射器、適配器、視圖解析器。
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"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-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd "><!-- 可以掃描controller、service、...這里讓掃描controller,指定controller的包--><context:component-scan base-package="joanna.yan.ssm.controller"></context:component-scan><!--注解映射器 --><!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/> --><!--注解適配器 --><!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/> --><!--使用mvc:annotation-driven代替上邊注解映射器和注解適配器 配置mvc:annotation-driven默認(rèn)加載很多的參數(shù)綁定方法,比如json轉(zhuǎn)換解析器就默認(rèn)加載了,如果使用mvc:annotation-driven就不用配置上面的RequestMappingHandlerMapping和RequestMappingHandlerAdapter實(shí)際開(kāi)發(fā)時(shí)使用mvc:annotation-driven--><mvc:annotation-driven></mvc:annotation-driven><!-- 配置視圖解析器 解析jsp視圖,默認(rèn)使用jstl標(biāo)簽,所有classpath下得有jstl的包--><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"><!--配置jsp路徑的前綴 --><property name="prefix" value="/WEB-INF/jsp/"/><!--配置jsp路徑的后綴 --><property name="suffix" value=".jsp"/></bean> </beans>6.2配置前端控制器
參考入門(mén)程序:Spring+SpringMVC+MyBatis深入學(xué)習(xí)及搭建(十二)——SpringMVC入門(mén)程序(一)
在web.xml中配置:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"><display-name>SpringMVC_MyBatis</display-name><welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list><!-- springmvc前端控制器 --><servlet><servlet-name>springmvc</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><!-- contextConfigLocation配置springmvc加載的配置文件(該配置文件中配置了處理器映射器、適配器等等) 如果不配置contextConfigLocation,默認(rèn)加載的是/WEB-INF/servlet名稱(chēng)-servlet.xml(即springmvc-servlet.xml)--><init-param><param-name>contextConfigLocation</param-name><param-value>classpath:spring/springmvc.xml</param-value></init-param><!-- 表示servlet隨服務(wù)啟動(dòng) --><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>springmvc</servlet-name><!--Servlet攔截方式方式一:*.action,訪問(wèn)以.action結(jié)尾由DispatcherServlet進(jìn)行解析方式二:/,所有訪問(wèn)的地址都由DispatcherServlet進(jìn)行解析,對(duì)于靜態(tài)文件的解析需要配置不讓DispatcherServlet進(jìn)行解析。使用此方式可以實(shí)現(xiàn)RESTful風(fēng)格的url方式三:/*,這樣配置不對(duì),使用這種配置,最終要轉(zhuǎn)發(fā)到一個(gè)jsp頁(yè)面時(shí),仍然會(huì)由DispatcherServlet解析jsp地址,不能根據(jù)jsp頁(yè)面找到handler,會(huì)報(bào)錯(cuò)--><url-pattern>*.action</url-pattern></servlet-mapping></web-app>6.3編寫(xiě)Controller(就是Handler)
@Controller public class ItemsController {@Autowiredprivate ItemsService itemsService;//商品查詢(xún)http://localhost:8080/SpringMVC_MyBatis/queryItems.action@RequestMapping("/queryItems")public ModelAndView queryItems() throws Exception{//調(diào)用service查找數(shù)據(jù)庫(kù),查詢(xún)商品列表List<ItemsCustom> itemsList=itemsService.findItemsList(null);//返回ModelAndViewModelAndView modelAndView=new ModelAndView();modelAndView.addObject("itemsList", itemsList);//指定視圖 // modelAndView.setViewName("/WEB-INF/jsp/items/itemsList.jsp");//下邊的路徑,如果在視圖解析器中配置jsp路徑的前綴和jsp路徑的后綴,修改為modelAndView.setViewName("items/itemsList");return modelAndView;} }6.4編寫(xiě)jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>查詢(xún)商品列表</title> </head> <body> <form action="${pageContext.request.contextPath }/item/queryItem.action" method="post"> 查詢(xún)條件: <table width="100%" border=1> <tr> <td><input type="submit" value="查詢(xún)"/></td> </tr> </table> 商品列表: <table width="100%" border=1> <tr><td>商品名稱(chēng)</td><td>商品價(jià)格</td><td>生產(chǎn)日期</td><td>商品描述</td><td>操作</td> </tr> <c:forEach items="${itemsList }" var="item"> <tr><td>${item.name }</td><td>${item.price }</td><td><fmt:formatDate value="${item.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/></td><td>${item.detail }</td><td><a href="${pageContext.request.contextPath }/item/editItem.action?id=${item.id}">修改</a></td></tr> </c:forEach></table> </form> </body></html>7.加載spring容器
將mapper、service、controller加載到spring容器中。
建議使用通配符加載上邊的配置文件。
在web.xml中添加spring容器監(jiān)聽(tīng)器,加載spring容器。
<!-- 加載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>8.商品查詢(xún)調(diào)試
訪問(wèn)地址:http://localhost:8080/SpringMVC_MyBatis/queryItems.action
查詢(xún)結(jié)果:
注意:在進(jìn)行項(xiàng)目發(fā)布時(shí),報(bào)錯(cuò)
javax.servlet.ServletException: Servlet.init() for servlet springmvc threw exceptionorg.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:620)org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)java.lang.Thread.run(Thread.java:745)原因:服務(wù)器上Tomcat的jdk版本過(guò)高是1.8,而Spring的jar是3.2。
解決:降低jdk版本至1.7或?qū)pring的jar升至4.0及以上。
如果此文對(duì)您有幫助,微信打賞我一下吧~?
?
轉(zhuǎn)載于:https://www.cnblogs.com/Joanna-Yan/p/7010363.html
總結(jié)
以上是生活随笔為你收集整理的Spring+SpringMVC+MyBatis深入学习及搭建(十四)——SpringMVC和MyBatis整合的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 51nod汽油补给
- 下一篇: 《软件工艺师:专业、务实、自豪》一3.7