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

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

SSM-Spring+SpringMVC+MyBatis整合案例从0到1

發(fā)布時間:2025/3/21 javascript 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 SSM-Spring+SpringMVC+MyBatis整合案例从0到1 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

文章目錄

  • 概述
  • Step1.新建Maven web項目
    • step1.1 基本結(jié)構(gòu)
    • Step1.2 pom.xml
    • Step1.3 web.xml
    • Step1.4 pom.xml中添加web的支持
    • Step1.5 添加頁面用于驗證搭建的web項目是否OK
  • Step2.集成Spring和Spring MVC
    • Step2.1 添加Spring項目清單用于管理Spring依賴
    • Step2.2 添加Spring依賴
    • Step2.3 添加Spring MVC依賴
    • Step2.4 添加Spring XML配置文件
    • Step2.5 添加Spring MVC配置文件
    • Step2.6 配置web.xml
    • Step2.7 驗證集成的Spring 以及SpringMVC是否OK
  • Step3.集成MyBatis
    • Step3.1 添加mybatis-spring依賴
    • Step3.2 配置 SqlSessionFactoryBean
    • Step3.3 配置MapperScannerConfigurer
    • 3.4applicationContext.xml其他配置AOP和事務(wù)
  • Step4.示例測試
    • step4.0數(shù)據(jù)準(zhǔn)備
    • step4.1 實體類
    • step4.2 開發(fā)Mapper層(Dao層)
      • 4.2.1 根據(jù)配置文件中的掃描路徑新建包(接口用)或目錄(xml用)
      • 4.2.2DictMapper接口
      • 4.2.3 DictMapper.xml
    • step4.3開發(fā)業(yè)務(wù)層(Service層)
    • step4.4開發(fā)控制層(Controller層)
    • step4.5開發(fā)視圖層(View層)
    • step4.6部署運行應(yīng)用
  • Step5.代碼地址及總結(jié)

概述

通過半個多月的梳理,MyBatis我們已經(jīng)能夠使用,下面我們來說下SSM的整合。

整合SSM,需要用到MyBatis-Spring。

MyBatis-Spring可以將MyBatis代碼無縫整合到Spring中,使用這個類庫中的類,Spring將會加載必要的MyBatis工廠類和Session類。 這個類庫也提供了一種簡單的方式將MyBatis數(shù)據(jù)映射器和SqlSession注入到業(yè)務(wù)層的bean中,而且也可以處理事務(wù),翻譯MyBatis的異常到Spring的DataAcessException數(shù)據(jù)訪問異常中。

MyBatis-Spring項目地址: https://github.com/mybatis/spring

接下來,我們從新建一個Maven項目開始,逐步集成Spring、Spring MVC 和MyBatis。


Step1.新建Maven web項目

如果不熟悉,請查考之前的博文總結(jié) Maven-EclipseEE使用Maven構(gòu)建Java web項目從0到1,這里簡單說下重點,不贅述細(xì)節(jié)了。


step1.1 基本結(jié)構(gòu)


Step1.2 pom.xml

正創(chuàng)建Maven Web項目的時候,輸入對應(yīng)的Group Id 、 Artifact Id 、 Version ,web項目 packing 為 war。


Step1.3 web.xml

<?xml version="1.0" encoding="ISO-8859-1"?> <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/javaeehttp://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"version="3.0"></web-app>

空的web.xml 如上所示,


Step1.4 pom.xml中添加web的支持

添加web的支持

<!--web--> <!-- servlet --> <dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>${servlet.version}</version><scope>provided</scope> </dependency> <!--JSP--> <dependency><groupId>javax.servlet.jsp</groupId><artifactId>jsp-api</artifactId><version>${jsp.version}</version><scope>provided</scope> </dependency> <!--JSTL--> <dependency><groupId>javax.servlet</groupId><artifactId>jstl</artifactId><version>${jstl.version}</version> </dependency>

版本信息如下:

<junit.version>3.8.1</junit.version> <servlet.version>3.1.0</servlet.version> <jstl.version>1.2</jstl.version> <jsp.version>2.1</jsp.version>

由于項目中可能會用到Filter和ServletRequest接口,所以在編譯項目時,必須聽servlet-api和jsp-api依賴。 通常Web容器都會自帶servlet-api和jsp-api的jar包,為了避免jar包重復(fù)引起錯誤,需要將servlet-api和jsp-api的scope配置為provided.

配置為provided的jar包在項目打包時,不會將依賴的jar包打包到項目中,項目運行時這些jar包需要歐容器提供,這樣避免了重復(fù)jar包引起的錯誤。

一般以JSP作為視圖的項目中,jstl是很常見的搭配,使用jstl可以在視圖中處理復(fù)雜的邏輯,所以都會添加jstl依賴


Step1.5 添加頁面用于驗證搭建的web項目是否OK

頁面中使用了jstl,用來顯示服務(wù)器的時間。

/ssm/src/main/webapp下添加個home.jsp

同時在web.xml中添加歡迎頁面

<!-- 關(guān)于歡迎頁面:訪問一個網(wǎng)站時,默認(rèn)看到的第一個頁面就叫歡迎頁,一般情況下是由首頁來充當(dāng)歡迎頁的。一般情況下,我們會在web.xml中指定歡迎頁。 --><!-- 指定歡迎頁面.指定了2個歡迎頁面.顯示時按順序從第一個找起,如果第一個存在,就顯示第一個,后面的不起作用。如果第一個不存在,就找第二個,以此類推 --><welcome-file-list><welcome-file>home.jsp</welcome-file><welcome-file>index.jsp</welcome-file></welcome-file-list><!-- web.xml也沒指定歡迎頁的情況下,它默認(rèn)先查找index.html文件,如果找到了,就把index.html作為歡迎頁還回給瀏覽器。如果沒找到index.html,tomcat就去找index.jsp。找到index.jsp就把它作為歡迎頁面返回。而如果index.html和index.jsp都沒找到,又沒有用web.xml文件指定歡迎頁面,那此時tomcat就不知道該返回哪個文件了,就顯示TThe requested resource is not available. -->

home.jsp

<%@ page import="java.util.Date" %> <%@ page language="java" contentType="text/html; charset=UTF8" pageEncoding="UTF8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/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=UTF8"><title>Home</title> </head> <body> <p>用于驗證新建的Maven Web項目是否OK<br><br>頁面以及服務(wù)器時間正常展示--->OK </p><p><%Date now = new Date();%>服務(wù)器時間:<fmt:formatDate value="<%=now%>" pattern="yyyy-MM-dd HH:mm:ss"/> </p> </body> </html>

將項目發(fā)布到tomcat8中

啟動成功后,輸入
http://localhost:8080/ssm/home.jsp
或者
http://localhost:8080/ssm


Step2.集成Spring和Spring MVC

Step2.1 添加Spring項目清單用于管理Spring依賴

<!-- 在dependencyManagement中引入spring-framework-bom來確保所有的spring模塊都使用統(tǒng)一的版本.添加spring-framework-bom后,就不需要配置每個依賴的版本號了,方便管理與升級 --><dependencyManagement><dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-framework-bom</artifactId><version>4.3.9.RELEASE</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement>

在dependencyManagement中引入spring-framework-bom來確保所有的spring模塊都使用統(tǒng)一的版本.添加spring-framework-bom后,就不需要配置每個依賴的版本號了,方便管理與升級


Step2.2 添加Spring依賴

<!--Spring 上下文,核心依賴--><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId></dependency><!--Spring JDBC--><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId></dependency><!--Spring 事務(wù)--><dependency><groupId>org.springframework</groupId><artifactId>spring-tx</artifactId></dependency><!--Spring 面向切面編程--><dependency><groupId>org.springframework</groupId><artifactId>spring-aop</artifactId></dependency><!--spring-aop 依賴--><dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>${aspectjweaver.version}</version></dependency>

詳見注釋內(nèi)容


Step2.3 添加Spring MVC依賴

<!--Spring Web 核心--><dependency><groupId>org.springframework</groupId><artifactId>spring-web</artifactId></dependency><!--Spring MVC--><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId></dependency><!--spring mvc-json依賴--><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.8.4</version></dependency>

前兩個依賴是SpringMVC必備的依賴,后面的jackson-databind是SpringMVC轉(zhuǎn)換為JSON時需要使用的依賴


Step2.4 添加Spring XML配置文件

/src/main/resources目錄下 增加 applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:tx="http://www.springframework.org/schema/tx"xmlns:aop="http://www.springframework.org/schema/aop"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"><!-- 配置Spring自動掃描類,通過base-package指定掃描的包名 使用了Ant通配符 --><context:component-scan base-package="com.artisan.*.service.impl"/><!-- 數(shù)據(jù)源 --><bean id="dataSource" class="org.apache.ibatis.datasource.pooled.PooledDataSource"><property name="driver" value="com.mysql.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/artisan"/><property name="username" value="root"/><property name="password" value="root"/></bean></beans>

配置文件中component-scan用于配置Spring自動掃描的類,通過base-package屬性設(shè)置要掃描的包名, 包名支持Ant通配符,報名中的*匹配0或者任意數(shù)量的字符,這里的配置可以匹配com.artisan.web.service.impl 或者 com.artisan.xxx.service.impl這樣的包。

dataSource配置了一個數(shù)據(jù)源連接,最好將其獨立到單獨的配置文件,前面的博客中有講,這里先不抽取出來了。


Step2.5 添加Spring MVC配置文件

/src/main/resources目錄下新增 springmvcConfig.xml

<?xml version="1.0" encoding="UTF-8"?> <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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd"><!-- 掃描控制層的注解,使其成為Spring管理的Bean --><context:component-scan base-package="com.artisan.*.controller"/><!-- 啟用Controller注解支持 --><mvc:annotation-driven/><!-- 靜態(tài)資源文件 --><mvc:resources mapping="/static/**" location="static/"/><!-- 視圖解析器 --><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/><property name="prefix" value="/WEB-INF/jsp/"/><property name="suffix" value=".jsp"/></bean></beans>

配置項說明參考注釋


Step2.6 配置web.xml

集成Spring和SpringMVC后,要在web.xml中進行相應(yīng)的配置。

對于Spring來說,需要增加如下配置

<!-- 在web啟動時,根據(jù)contextConfigLocation配置的路徑讀取Spring配置文件,啟動Spring --><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:applicationContext.xml</param-value></context-param><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener>

對于Spring MVC來說,需要增加如下配置

<!-- Spring MVC配置 --><servlet><servlet-name>springmvc</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><param-name>contextConfigLocation</param-name><param-value>classpath:springmvcConfig.xml</param-value></init-param><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>springmvc</servlet-name><url-pattern>/</url-pattern></servlet-mapping>

為了避免編碼不一致,通常還需要增加編碼過濾器配置

<!-- 為避免編碼不一致,一般情況下都需要增加編碼過濾器 --><filter><filter-name>SpringEncodingFilter</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><init-param><param-name>forceEncoding</param-name><param-value>true</param-value></init-param></filter><filter-mapping><filter-name>SpringEncodingFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping>

Step2.7 驗證集成的Spring 以及SpringMVC是否OK

/ssm/src/main/webapp/WEB-INF/jsp目錄下增加 index.jsp

<%@ page language="java" contentType="text/html; charset=UTF8" pageEncoding="UTF8"%> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/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=UTF8"><title>Index</title> </head> <body> <p>用于驗證集成了Spring和SpringMVC是否正常<br><br>頁面以及服務(wù)器時間正常展示--->OK </p><p> 通過mv傳遞過來的now視圖參數(shù),獲取服務(wù)器時間服務(wù)器時間:<fmt:formatDate value="${now}" pattern="yyyy-MM-dd HH:mm:ss"/> </p> </body> </html>

/ssm/src/main/java/com/artisan/web/controller包下增加控制層IndexController.java

package com.artisan.web.controller;import java.util.Date;import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView;/*** * * @ClassName: IndexController* * @Description: 用于驗證集成Spring以及SpringMVC是否OK* * @author: Mr.Yang* * @date: 2018年5月1日 下午2:21:11*/@Controller public class IndexController {@RequestMapping("/index")public ModelAndView testEnv() {ModelAndView mv = new ModelAndView();// 設(shè)置跳轉(zhuǎn)頁面mv.setViewName("index");// 傳遞參數(shù)mv.addObject("now", new Date());return mv;} }

啟動應(yīng)用,訪問 http://localhost:8080/ssm/index


Step3.集成MyBatis

Step3.1 添加mybatis-spring依賴

<dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>${mybatis-spring}</version></dependency>

這里我們使用 <mybatis-spring>1.3.0</mybatis-spring>版本


Step3.2 配置 SqlSessionFactoryBean

在MyBatis-Spring中,SqlSessionFactoryBean用于創(chuàng)建SqlSessionFactory. 在Spring配置文件applicationContext.xml中配置這個工廠類

<!-- 配置SqlSessionFactory --><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><property name="configLocation" value="classpath:mybatisConfig.xml"/><property name="dataSource" ref="dataSource"/><property name="mapperLocations"><array><value>classpath:com/artisan/**/mapper/*.xml</value></array></property><property name="typeAliasesPackage" value="com.artisan.web.model"/></bean>

SqlSessionFactoryBean常用屬性介紹:

  • configLocation 用于配置MyBatis配置XML的路徑

MyBatis配置文件 /ssm/src/main/resources/mybatisConfig.xml

<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration><settings><setting name="logImpl" value="LOG4J"/><setting name="cacheEnabled" value="true"/><setting name="mapUnderscoreToCamelCase" value="true"/><setting name="aggressiveLazyLoading" value="false"/></settings> </configuration>
  • datasource 用于配置數(shù)據(jù)源,必選項

  • mapperLocations 配置SqlSessionFactory掃描XML映射文件的路徑

  • typeAliasesPackage 配置包中類的別名, 配置后,包中的類在XML映射文件中使用時可以省略包名部分,直接使用類名。 不支持Ant風(fēng)格的路徑,當(dāng)需要配置多個可以使用分號或者逗號隔開。

其他屬性可參考源碼,略。


Step3.3 配置MapperScannerConfigurer

推薦使用MapperScannerConfigurer 類自動掃描所有的Mapper接口,使用時可以直接注入接口

/ssm/src/main/resources/applicationContext.xml增加

<!-- 配置MapperScannerConfigurer --><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="addToConfig" value="true"/><property name="basePackage" value="com.artisan.**.mapper"/></bean>

MapperScannerConfigurer常用屬性

  • basePackage 用于配置基本的包路徑,可以使用分號或者逗號作為分隔符設(shè)置多個包路徑,每個映射器會在指定的包路徑中遞歸被搜索到。

  • annotationClass 用于過濾被掃描的接口,如果設(shè)置了該屬性,那么MyBatis的接口只有包含該注解才會被掃描進去。


3.4applicationContext.xml其他配置AOP和事務(wù)

<aop:aspectj-autoproxy/><aop:config><aop:pointcut id="appService" expression="execution(* com.artisan.*.service..*Service*.*(..))"/><aop:advisor advice-ref="txAdvice" pointcut-ref="appService"/></aop:config><tx:advice id="txAdvice" transaction-manager="transactionManager"><tx:attributes><tx:method name="select*" read-only="true"/><tx:method name="find*" read-only="true"/><tx:method name="get*" read-only="true"/><tx:method name="*"/></tx:attributes></tx:advice><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource"/></bean>

Step4.示例測試

step4.0數(shù)據(jù)準(zhǔn)備

MySql數(shù)據(jù)庫

-- ---------------------------- -- Table structure for sys_dict -- ---------------------------- DROP TABLE IF EXISTS `sys_dict`; CREATE TABLE `sys_dict` (`id` bigint(32) NOT NULL AUTO_INCREMENT COMMENT '主鍵',`code` varchar(64) NOT NULL COMMENT '類別',`name` varchar(64) NOT NULL COMMENT '字典名',`value` varchar(64) NOT NULL COMMENT '字典值',PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;-- ---------------------------- -- Records of sys_dict -- ---------------------------- INSERT INTO `sys_dict` VALUES ('1', '性別', '男', '男'); INSERT INTO `sys_dict` VALUES ('2', '性別', '女', '女'); INSERT INTO `sys_dict` VALUES ('3', '季度', '第一季度', '1'); INSERT INTO `sys_dict` VALUES ('4', '季度', '第二季度', '2'); INSERT INTO `sys_dict` VALUES ('5', '季度', '第三季度', '3'); INSERT INTO `sys_dict` VALUES ('6', '季度', '第四季度', '4');

step4.1 實體類

在 /src/main/java 新建 com.artisan.web.model包,然后新建SysDict.java

package com.artisan.web.model;import java.io.Serializable;/*** * * @ClassName: SysDict* * @Description: SysDict實體類,如果使用緩存,請務(wù)必實現(xiàn)java.io.Serializable接口* * @author: Mr.Yang* * @date: 2018年5月11日 下午4:16:37*/ public class SysDict implements Serializable {private static final long serialVersionUID = -2496324675593406906L;private Long id;private String code;private String name;private String value;public Long getId() {return id;}public void setId(Long id) {this.id = id;}public String getCode() {return code;}public void setCode(String code) {this.code = code;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getValue() {return value;}public void setValue(String value) {this.value = value;}@Overridepublic String toString() {return "SysDict [id=" + id + ", code=" + code + ", name=" + name + ", value=" + value + "]";}}

step4.2 開發(fā)Mapper層(Dao層)

Mapper層也就是常說的數(shù)據(jù)訪問層(Dao層) 。 使用Mapper和XML映射文件結(jié)合的方式進行開發(fā)。

4.2.1 根據(jù)配置文件中的掃描路徑新建包(接口用)或目錄(xml用)

在/ssm/src/main/resources/applicationContext.xml集成MyBatis中

MapperScannerConfigurer自動掃描接口的包名為 com.artisan.**.mapper,因此創(chuàng)建Mapper接口也需要參照這個命名規(guī)則。

在/src/main/java新建 com.artisan.web.mapper 包,創(chuàng)建DictMapper接口

public interface DictMapper {}

同樣的,SqlSessionFactoryBean中配置了掃描XML映射文件的路徑

classpath:com/artisan/**/mapper/*.xml ,在 /src/main/resources/ 新建com/artisan/web/mapper目錄,然后新增DictMapper.xml文件

<?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" ><!-- 當(dāng)Mapper接口和XML文件關(guān)聯(lián)的時候, namespace的值就需要配置成接口的全限定名稱 --> <mapper namespace="com.artisan.web.mapper.DictMapper"></mapper>

4.2.2DictMapper接口

CRUD基本操作

package com.artisan.web.mapper;import java.util.List;import org.apache.ibatis.session.RowBounds;import com.artisan.web.model.SysDict;/*** * * @ClassName: DictMapper* * @Description: 操作Sys_Dict的接口* * @author: Mr.Yang* * @date: 2018年5月11日 下午4:24:14*/public interface DictMapper {/*** * * @Title: selectByPrimaryKey* * @Description: 根據(jù)主鍵查詢* * @param id* @return* * @return: SysDict*/SysDict selectByPrimaryKey(Long id);/*** 條件查詢** @param sysDict* @return*/List<SysDict> selectBySysDict(SysDict sysDict, RowBounds rowBounds);/*** 新增** @param sysDict* @return*/int insert(SysDict sysDict);/*** 根據(jù)主鍵更新** @param sysDict* @return*/int updateById(SysDict sysDict);/*** 根據(jù)主鍵刪除** @param id* @return*/int deleteById(Long id); }

4.2.3 DictMapper.xml

<?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" ><!-- 當(dāng)Mapper接口和XML文件關(guān)聯(lián)的時候, namespace的值就需要配置成接口的全限定名稱 --> <mapper namespace="com.artisan.web.mapper.DictMapper"><select id="selectByPrimaryKey" resultType="com.artisan.web.model.SysDict">SELECTa.id,a.`code`,a.`name`,a.`value`FROMsys_dict aWHEREa.id = #{id}</select><select id="selectBySysDict" resultType="com.artisan.web.model.SysDict">select * from sys_dict<where><if test="id != null">and id = #{id}</if><if test="code != null and code != ''">and code = #{code}</if></where>order by code, `value`</select><insert id="insert" useGeneratedKeys="true" keyProperty="id">insertinto sys_dict(code, name, value)values (#{code}, #{name}, #{value})</insert><update id="updateById">update sys_dictset code = #{code},name = #{name},value = #{value}where id = #{id}</update><delete id="deleteById">delete from sys_dict where id = #{id}</delete></mapper>

有了上述5個方法,就可以實現(xiàn)對表的基本操作了,下面在這5個接口方法的基礎(chǔ)上繼續(xù)開發(fā)Service層的代碼。


step4.3開發(fā)業(yè)務(wù)層(Service層)

src/main/java 目錄下新建 com.artisan.web.service包 ,添加DictService接口

package com.artisan.web.service;import java.util.List;import com.artisan.web.model.SysDict;/*** * * @ClassName: DictService* * @Description: Service層* * @author: Mr.Yang* * @date: 2018年5月11日 下午5:37:22*/ public interface DictService {SysDict findById(Long id);List<SysDict> findBySysDict(SysDict sysDict, Integer offset, Integer limit);boolean saveOrUpdate(SysDict sysDict);boolean deleteById(Long id); }

Servie層的saveOrUpdate方法對應(yīng)Mapper中的insert和updateById方法,其他3個方法和Mapper層的方法一一對應(yīng)。

com.artisan.web.service包下新建 impl包,然后新建DictServiceImpl實現(xiàn)類實現(xiàn)該接口

接口實現(xiàn)類

package com.artisan.web.service.impl;import java.util.List;import org.apache.ibatis.session.RowBounds; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;import com.artisan.web.mapper.DictMapper; import com.artisan.web.model.SysDict; import com.artisan.web.service.DictService; /*** * @ClassName: DictServiceImpl* @Description: @Service標(biāo)注的Service層* @author: Mr.Yang* @date: 2018年5月11日 下午5:39:22*/@Service public class DictServiceImpl implements DictService {@Autowiredprivate DictMapper dictMapper;@Overridepublic SysDict findById(Long id) {return dictMapper.selectByPrimaryKey(id);}@Overridepublic List<SysDict> findBySysDict(SysDict sysDict, Integer offset, Integer limit) {RowBounds rowBounds = RowBounds.DEFAULT;if (offset != null && limit != null) {rowBounds = new RowBounds(offset, limit);}return dictMapper.selectBySysDict(sysDict, rowBounds);}@Overridepublic boolean saveOrUpdate(SysDict sysDict) {if (sysDict.getId() == null) {return dictMapper.insert(sysDict) == 1;} else {return dictMapper.updateById(sysDict) == 1;}}@Overridepublic boolean deleteById(Long id) {if (id == null) {throw new NullPointerException("id");}return dictMapper.deleteById(id) == 1;}}

Service層的實現(xiàn)類需要添加@Service注解,集成Spring的時候配置過自動掃描包

/ssm/src/main/resources/applicationContext.xml

包名com.artisan.web.service.impl, DictServiceImpl實現(xiàn)類所在的包就是符合這個包名規(guī)則,加上注解后,Spring在初始化掃描到這個類時,然后由Spring管理這個類。

同樣的,因為配置了自動掃描Mapper接口,所以在Service層可以注解通過@Autowired自動注入Mapper

通過自動掃描Mapper和自動注入可以更加方便的使用MyBatis。


step4.4開發(fā)控制層(Controller層)

com.artisan.web.controller包下新建DictController類

package com.artisan.web.controller;import java.util.List;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView;import com.artisan.web.model.SysDict; import com.artisan.web.service.DictService;/*** * * @ClassName: DictController* * @Description: @Controller標(biāo)注的Dict控制層* * @author: Mr.Yang* * @date: 2018年5月11日 下午5:40:19*/@Controller @RequestMapping("/dicts") public class DictController {@Autowiredprivate DictService dictService;/*** 顯示字典數(shù)據(jù)列表* * @param sysDict* @param offset* @param limit* @return*/@RequestMappingpublic ModelAndView dicts(SysDict sysDict, Integer offset, Integer limit) {ModelAndView mv = new ModelAndView("dicts");List<SysDict> dicts = dictService.findBySysDict(sysDict, offset, limit);mv.addObject("dicts", dicts);return mv;}/*** 新增或修改字典信息頁面,使用 get 跳轉(zhuǎn)到頁面* * @param id* @return*/@RequestMapping(value = "add", method = RequestMethod.GET)public ModelAndView add(Long id) {ModelAndView mv = new ModelAndView("dict_add");SysDict sysDict;if (id == null) {// 如果 id 不存在,就是新增數(shù)據(jù),創(chuàng)建一個空對象即可sysDict = new SysDict();} else {// 如果 id 存在,就是修改數(shù)據(jù),把原有的數(shù)據(jù)查詢出來sysDict = dictService.findById(id);}mv.addObject("model", sysDict);return mv;}/*** 新增或修改字典信息,通過表單 post 提交數(shù)據(jù)* * @param sysDict* @return*/@RequestMapping(value = "add", method = RequestMethod.POST)public ModelAndView save(SysDict sysDict) {ModelAndView mv = new ModelAndView();try {dictService.saveOrUpdate(sysDict);mv.setViewName("redirect:/dicts");} catch (Exception e) {mv.setViewName("dict_add");mv.addObject("msg", e.getMessage());mv.addObject("model", sysDict);}return mv;}/*** 通過 id 刪除字典信息* * @param id* @return*/@RequestMapping(value = "delete", method = RequestMethod.POST)@ResponseBodypublic ModelMap delete(@RequestParam Long id) {ModelMap modelMap = new ModelMap();try {boolean success = dictService.deleteById(id);modelMap.put("success", success);} catch (Exception e) {modelMap.put("success", false);modelMap.put("msg", e.getMessage());}return modelMap;} }

用了兩個視圖 dicts和 dict_add ,接下來開發(fā)View層


step4.5開發(fā)視圖層(View層)

/ssm/src/main/resources/springmvcConfig.xml中的配置

/ssm/src/main/webapp/WEB-INF/jsp/dicts.jsp

<%@ page language="java" contentType="text/html; charset=UTF8" pageEncoding="UTF8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head><c:set var="path" value="${pageContext.request.contextPath}"/><meta http-equiv="Content-Type" content="text/html; charset=UTF8"><title>字典信息</title><script src="${path}/static/jquery-3.1.1.min.js"></script> </head> <body> <table><tr><th colspan="4">字典管理</th></tr><tr><th>類別名</th><th>字典名</th><th>字典值</th><th> 操作 [<a href="${path}/dicts/add">新增</a>]</th></tr><c:forEach items="${dicts}" var="dict"><tr id="dict-${dict.id}"><td>${dict.code}</td><td>${dict.name}</td><td>${dict.value}</td><td>[<a href="${path}/dicts/add?id=${dict.id}">編輯</a>][<a href="javascript:;" onclick="deleteById(${dict.id}, '${dict.name}')">刪除</a>]</td></tr></c:forEach> </table> <script>function deleteById(id, label){var r = confirm('您確定要刪除“' + label + '”嗎?');if(r){$.ajax({url: '${path}/dicts/delete',data: {id: id},dataType: 'json',type: 'POST',success: function(data){if(data.success){$('#dict-' + id).remove();} else {alert(data.msg);}}})}} </script> </body> </html>

/ssm/src/main/webapp/WEB-INF/jsp/dict_add.jsp

<%@ page language="java" contentType="text/html; charset=UTF8" pageEncoding="UTF8" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head><c:set var="path" value="${pageContext.request.contextPath}"/><meta http-equiv="Content-Type" content="text/html; charset=UTF8"><title>字典維護</title> </head> <body> <form action="${path}/dicts/add" method="post"><input type="hidden" name="id" value="${model.id}"><table><c:if test="${msg != null}"><tr><th colspan="2" style="color:red;max-width:400px;">${msg}</th></tr></c:if><tr><th colspan="2">字典維護</th></tr><tr><th>類別名</th><td><input type="text" name="code" value="${model.code}"></td></tr><tr><th>字典名</th><td><input type="text" name="name" value="${model.name}"></td></tr><tr><th>字典值</th><td><input type="text" name="value" value="${model.value}"></td></tr><tr><th colspan="2"><input type="submit" value="保存"><input type="button" onclick="backToList()" value="取消"></th></tr></table> </form> <script>function backToList(){location.href = '${path}/dicts';} </script> </body> </html>

其中dicts.jsp使用了jquery-3.1.1.min.js ,請放在 /ssm/src/main/webapp/static/目錄下

step4.6部署運行應(yīng)用

發(fā)布到tomcat8中,訪問 http://localhost:8080/ssm/dicts

列表頁面:

新增

編輯

刪除一條我們新增的數(shù)據(jù)


Step5.代碼地址及總結(jié)

代碼已經(jīng)提交Github https://github.com/yangshangwei/ssm

本篇博客我們按照順序依次講解了如何集成Spring + Spring MVC + MyBatis ,通過該示例了解了配置和基本的數(shù)據(jù)操作方法。

總結(jié)

以上是生活随笔為你收集整理的SSM-Spring+SpringMVC+MyBatis整合案例从0到1的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。