日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

Spring+SpringMVC+MyBatis深入学习及搭建(十四)——SpringMVC和MyBatis整合

發(fā)布時間:2025/7/14 javascript 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Spring+SpringMVC+MyBatis深入学习及搭建(十四)——SpringMVC和MyBatis整合 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

轉載請注明出處:http://www.cnblogs.com/Joanna-Yan/p/7010363.html?

前面講到:Spring+SpringMVC+MyBatis深入學習及搭建(十三)——SpringMVC入門程序(二)

1.需求

使用springmvc和mybatis完成商品列表查詢。

2.整合思路

springmvc+mybatis的系統(tǒng)架構:

第一步:整合dao層

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

  使用mapper的掃描器自動掃描mapper接口在spring中進行注冊。

第二步:整合service層

  通過spring管理service接口。

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

  實現(xiàn)事務控制。

第三步:整合springMvc

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

3.環(huán)境準備

數(shù)據(jù)庫環(huán)境:mysql5.6

java環(huán)境:

jdk1.7

MyEclipse2014

springmvc版本:spring3.2

所需要的jar包:

數(shù)據(jù)庫驅動包

mybatis的jar包

mybatis的spring的整合包

log4j包

dbcp數(shù)據(jù)庫連接池包

spring3.2所有jar包

jstl包

過程結構目錄:

4.整合dao

?mybatis和spring進行整合。

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,建議開發(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%n

4.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的整合包進行mapper掃描,這里不需要配置了。但是必須遵循:mapper.xml和mapper.java文件同名且在一個目錄--><!-- <mappers></mappers> --></configuration>

4.4 applicationContext-dao.xml

在classpath下創(chuàng)建spring/applicationContext-dao.xml。配置:數(shù)據(jù)源、事務管理、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文件中的內容,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ù)庫連接池 --><property name="dataSource" ref="dataSource" /></bean><!-- mapper掃描器 --><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><!-- 掃描包路徑,如果需要掃描多個包,中間使用半角逗號隔開 --><property name="basePackage" value="joanna.yan.ssm.mapper"/><property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/></bean></beans>

4.5逆向工程生成po類及mapper(即單表增刪改查)

詳情見:Spring+SpringMVC+MyBatis深入學習及搭建(十)——MyBatis逆向工程

將生成的文件拷貝至工程中。

4.6手動定義商品查詢mapper

針對綜合查詢mapper,一般情況會有關聯(lián)查詢,建議自定義mapper。

4.6.1 ItemsMapperCustom.xml

sql語句:

???????? 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" ><!-- 定義商品查詢的sql片段,就是商品查詢條件 --><sql id="query_items_where"><!-- 使用動態(tài)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="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 {//商品查詢列表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 {//商品查詢列表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 {//通過ItemsMapperCustom查詢數(shù)據(jù)庫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事務控制(applicationContext-transaction.xml)

在classpath下創(chuàng)建spring/applicationContext-service.xml,文件中使用spring聲明式事務控制方法。

<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 "><!-- 事務管理器對mybatis操作數(shù)據(jù)庫事務控制,spring使用jdbc的事務控制類--><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開頭,update開頭等,不能想怎么命名就怎么命名 --><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"/> <!-- 支持,如果沒有就算了 --><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><!-- 切入點為joanna.yan.ssm.service.impl包下所有類的所有方法,不管里面什么參數(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默認加載很多的參數(shù)綁定方法,比如json轉換解析器就默認加載了,如果使用mvc:annotation-driven就不用配置上面的RequestMappingHandlerMapping和RequestMappingHandlerAdapter實際開發(fā)時使用mvc:annotation-driven--><mvc:annotation-driven></mvc:annotation-driven><!-- 配置視圖解析器 解析jsp視圖,默認使用jstl標簽,所有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配置前端控制器

參考入門程序:Spring+SpringMVC+MyBatis深入學習及搭建(十二)——SpringMVC入門程序(一)

在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,默認加載的是/WEB-INF/servlet名稱-servlet.xml(即springmvc-servlet.xml)--><init-param><param-name>contextConfigLocation</param-name><param-value>classpath:spring/springmvc.xml</param-value></init-param><!-- 表示servlet隨服務啟動 --><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>springmvc</servlet-name><!--Servlet攔截方式方式一:*.action,訪問以.action結尾由DispatcherServlet進行解析方式二:/,所有訪問的地址都由DispatcherServlet進行解析,對于靜態(tài)文件的解析需要配置不讓DispatcherServlet進行解析。使用此方式可以實現(xiàn)RESTful風格的url方式三:/*,這樣配置不對,使用這種配置,最終要轉發(fā)到一個jsp頁面時,仍然會由DispatcherServlet解析jsp地址,不能根據(jù)jsp頁面找到handler,會報錯--><url-pattern>*.action</url-pattern></servlet-mapping></web-app>

6.3編寫Controller(就是Handler)

@Controller public class ItemsController {@Autowiredprivate ItemsService itemsService;//商品查詢http://localhost:8080/SpringMVC_MyBatis/queryItems.action@RequestMapping("/queryItems")public ModelAndView queryItems() throws Exception{//調用service查找數(shù)據(jù)庫,查詢商品列表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編寫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>查詢商品列表</title> </head> <body> <form action="${pageContext.request.contextPath }/item/queryItem.action" method="post"> 查詢條件: <table width="100%" border=1> <tr> <td><input type="submit" value="查詢"/></td> </tr> </table> 商品列表: <table width="100%" border=1> <tr><td>商品名稱</td><td>商品價格</td><td>生產日期</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)聽器,加載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.商品查詢調試

訪問地址:http://localhost:8080/SpringMVC_MyBatis/queryItems.action

查詢結果:

注意:在進行項目發(fā)布時,報錯

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)

原因:服務器上Tomcat的jdk版本過高是1.8,而Spring的jar是3.2。

解決:降低jdk版本至1.7或將Spring的jar升至4.0及以上。

如果此文對您有幫助,微信打賞我一下吧~?

?

轉載于:https://www.cnblogs.com/Joanna-Yan/p/7010363.html

總結

以上是生活随笔為你收集整理的Spring+SpringMVC+MyBatis深入学习及搭建(十四)——SpringMVC和MyBatis整合的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。