Java PostMan SpringMVC:SSM整合(SpringMVC+Spring+Mybatis)案例(9) - @Update(&#34

📅 2026-11-30 👤 拼多多助力营销技巧 📂 首码项目 👁️ 168 次阅读

SSM整合

1. 整体流程分析2. 整合配置2.1 创建Maven项目2.2 添加依赖2.3 创建项目包结构2.4 创建jdbc.properties2.5 创建JdbcConfig配置类2.6 创建MybatisConfig配置类2.7 创建SpringConfig配置类2.8 创建SpringMVC配置类2.9 创建Web项目入口配置类2.10 总体架构

3. 功能模块开发3.1 创建数据库及表3.2 编写模型类3.3 编写Dao接口3.4 编写Service接口和实现类3.5 编写Controller类3.6 总体架构

4. 单元测试4.1 新建测试类4.2 注入Service类4.3 新增测试方法4.4 修改测试方法4.5 删除测试方法4.6 查询单个测试方法4.7 查询所有测试方法

5. PostMan测试启动Tomcat5.1 新增5.2 修改5.3 删除5.4 查询单个5.5 查询所有

6 总结

1. 整体流程分析

(1) 创建工程

创建一个Maven的web工程pom.xml添加SSM需要的依赖jar包编写Web项目的入口配置类,实现AbstractAnnotationConfigDispatcherServletInitializer重写以下方法

getRootConfigClasses() :返回Spring的配置类->需要SpringConfig配置类getServletConfigClasses() :返回SpringMVC的配置类->需要SpringMvcConfig配置类getServletMappings() : 设置SpringMVC请求拦截路径规则getServletFilters() :设置过滤器,解决POST请求中文乱码问题

(2) SSM整合[重点是各个配置的编写]

SpringConfig

标识该类为配置类 @Configuration扫描Service所在的包 @ComponentScan在Service层要管理事务 @EnableTransactionManagement读取外部的properties配置文件 @PropertySource整合Mybatis需要引入Mybatis相关配置类 @Import

第三方数据源配置类 JdbcConfig

构建DataSource数据源,DruidDataSouroce,需要注入数据库连接四要素, @Bean @Value构建平台事务管理器,DataSourceTransactionManager,@Bean Mybatis配置类 MybatisConfig

构建SqlSessionFactoryBean并设置别名扫描与数据源,@Bean构建MapperScannerConfigurer并设置DAO层的包扫描 SpringMvcConfig

标识该类为配置类 @Configuration扫描Controller所在的包 @ComponentScan开启SpringMVC注解支持 @EnableWebMvc

(3) 功能模块[与具体的业务模块有关]

创建数据库表根据数据库表创建对应的模型类通过Dao层完成数据库表的增删改查(接口+自动代理)编写Service层[Service接口+实现类]

@Service@Transactional整合Junit对业务层进行单元测试

@RunWith@ContextConfiguration@Test 编写Controller层

接收请求 @RequestMapping @GetMapping @PostMapping @PutMapping @DeleteMapping接收数据 简单、POJO、嵌套POJO、集合、数组、JSON数据类型

@RequestParam@PathVariable@RequestBody 转发业务层

@Autowired 响应结果

@ResponseBody

2. 整合配置

2.1 创建Maven项目

2.2 添加依赖

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

4.0.0

org.example

springMvc_09_SSM

1.0-SNAPSHOT

war

org.springframework

spring-jdbc

5.2.10.RELEASE

org.springframework

spring-test

5.2.10.RELEASE

org.mybatis

mybatis

3.5.6

log4j

log4j

1.2.17

org.mybatis

mybatis-spring

1.3.0

mysql

mysql-connector-java

5.1.47

com.alibaba

druid

1.1.16

junit

junit

4.12

test

javax.servlet

javax.servlet-api

3.1.0

provided

org.springframework

spring-webmvc

5.2.10.RELEASE

com.fasterxml.jackson.core

jackson-databind

2.9.0

8

8

org.apache.tomcat.maven

tomcat7-maven-plugin

2.2

8080

/

UTF-8

2.3 创建项目包结构

2.4 创建jdbc.properties

2.5 创建JdbcConfig配置类

JdbcConfig配置类:

import com.alibaba.druid.pool.DruidDataSource;

import org.springframework.beans.factory.annotation.Value;

import org.springframework.context.annotation.Bean;

import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

public class JdbcConfig {

@Value("${jdbc.driver}")

private String driver;

@Value("${jdbc.url}")

private String url;

@Value("${jdbc.username}")

private String username;

@Value("${jdbc.password}")

private String password;

@Bean

public DataSource dataSource(){

DruidDataSource dataSource = new DruidDataSource();

dataSource.setDriverClassName(driver);

dataSource.setUrl(url);

dataSource.setUsername(username);

dataSource.setPassword(password);

return dataSource;

}

@Bean

public PlatformTransactionManager transactionManager(DataSource dataSource){

DataSourceTransactionManager ds = new DataSourceTransactionManager();

ds.setDataSource(dataSource);

return ds;

}

}

2.6 创建MybatisConfig配置类

MybatisConfig配置类:

import org.mybatis.spring.SqlSessionFactoryBean;

import org.mybatis.spring.mapper.MapperScannerConfigurer;

import org.springframework.context.annotation.Bean;

import javax.sql.DataSource;

public class MyBatisConfig {

@Bean

public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){

SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();

factoryBean.setDataSource(dataSource);

factoryBean.setTypeAliasesPackage("com.itheima.domain");

return factoryBean;

}

@Bean

public MapperScannerConfigurer mapperScannerConfigurer(){

MapperScannerConfigurer msc = new MapperScannerConfigurer();

msc.setBasePackage("com.itheima.dao");

return msc;

}

}

2.7 创建SpringConfig配置类

SpringConfig配置类

import org.springframework.context.annotation.*;

import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration

@ComponentScan({"com.itheima.service"}) // 扫描业务层包

@PropertySource("classpath:jdbc.properties") // 引入资源文件

@Import({JdbcConfig.class, MyBatisConfig.class}) // 导入JdbcConfig和MyBatisConfig配置文件

@EnableTransactionManagement // 事务注解

public class SpringConfig {

}

2.8 创建SpringMVC配置类

SpringMVC配置类

import org.springframework.context.annotation.ComponentScan;

import org.springframework.context.annotation.Configuration;

import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@Configuration

@ComponentScan("com.itheima.controller")

@EnableWebMvc // 开启json转换功能

public class SpringMvcConfig {

}

2.9 创建Web项目入口配置类

import org.springframework.web.context.WebApplicationContext;

import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;

import org.springframework.web.filter.CharacterEncodingFilter;

import org.springframework.web.servlet.support.AbstractDispatcherServletInitializer;

import javax.servlet.Filter;

public class ServletContainersInitConfig extends AbstractDispatcherServletInitializer {

/**

* 加载springmvc配置类

*

* @return

*/

@Override

protected WebApplicationContext createServletApplicationContext() {

AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();

ctx.register(SpringMvcConfig.class);

return ctx;

}

/**

* 设置由springmvc控制器处理的请求映射路径

*

* @return

*/

@Override

protected String[] getServletMappings() {

return new String[]{"/"};

}

/**

* 加载spring配置类

*

* @return

*/

@Override

protected WebApplicationContext createRootApplicationContext() {

AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();

ctx.register(SpringConfig.class);

return ctx;

}

// 乱码处理

@Override

protected Filter[] getServletFilters() {

CharacterEncodingFilter filter = new CharacterEncodingFilter();

filter.setEncoding("UTF-8");

return new Filter[]{filter};

}

}

2.10 总体架构

3. 功能模块开发

3.1 创建数据库及表

create database ssm_db character set utf8;

use ssm_db;

create table tb_book(

id int primary key auto_increment,

type varchar(20),

name varchar(50),

description varchar(255)

) 拼多多帮助力入口

insert into `tb_book`(`id`,`type`,`name`,`description`)

values (1,'计算机理论','Spring实战 第五版','Spring入门经典教程,深入理解Spring原理技术内幕'),

(2,'计算机理论','Spring 5核心原理与30个类手写实践','十年沉淀之作,手写Spring精华思想'),

(3,'计算机理论','Spring 5设计模式','深入Spring源码刨析Spring源码中蕴含的10大设计模式'),

(4,'计算机理论','Spring MVC+Mybatis开发从入门到项目实战','全方位解析面向Web应用的轻量级框架,带你成为Spring MVC开发高手'),(5,'计算机理论','轻量级Java Web企业应用实战','源码级刨析Spring框架,适合已掌握Java基础的读者'),

(6,'计算机理论','Java核心技术 卷Ⅰ 基础知识(原书第11版)','Core Java第11版,Jolt大奖获奖作品,针对Java SE9、10、11全面更新'),

(7,'计算机理论','深入理解Java虚拟机','5个纬度全面刨析JVM,大厂面试知识点全覆盖'),

(8,'计算机理论','Java编程思想(第4版)','Java学习必读经典,殿堂级著作!赢得了全球程序员的广泛赞誉'),

(9,'计算机理论','零基础学Java(全彩版)','零基础自学编程的入门图书,由浅入深,详解Java语言的编程思想和核心技术'),

(10,'市场营销','直播就这么做:主播高效沟通实战指南','李子柒、李佳奇、薇娅成长为网红的秘密都在书中'),

(11,'市场营销','直播销讲实战一本通','和秋叶一起学系列网络营销书籍'),

(12,'市场营销','直播带货:淘宝、天猫直播从新手到高手','一本教你如何玩转直播的书,10堂课轻松实现带货月入3W+');

3.2 编写模型类

public class Book {

private Integer id;

private String type;

private String name;

private String description;

//getter...setter...toString省略

}

3.3 编写Dao接口

package com.itheima.dao;

import com.itheima.domain.Book;

import org.apache.ibatis.annotations.Delete;

import org.apache.ibatis.annotations.Insert;

import org.apache.ibatis.annotations.Select;

import org.apache.ibatis.annotations.Update;

import org.springframework.stereotype.Repository;

import java.util.List;

public interface BookDao {

@Insert("insert into tb_book values(null, #{type}, #{name}, #{description})")

public void save(Book book);

@Update("update tb_book set type = #{type}, name = #{name}, description = #{description} where id = #{id}")

public void update(Book book);

@Delete("delete from tb_book where id = #{id}")

public void delete(Integer id);

@Select("select * from tb_book where id = #{id}")

public Book getById(Integer id);

@Select("select * from tb_book")

public ListgetAll();

}

3.4 编写Service接口和实现类

import com.itheima.domain.Book;

import org.apache.ibatis.annotations.Delete;

import org.apache.ibatis.annotations.Insert;

import org.apache.ibatis.annotations.Select;

import org.apache.ibatis.annotations.Update;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Transactional

public interface BookService {

/**

* 保存

* @param book

* @return

*/

public boolean save(Book book);

/**

* 修改

* @param book

* @return

*/

public boolean update(Book book);

/**

* 删除

* @param id

* @return

*/

public boolean delete(Integer id);

/**

* 按id进行查询

* @param id

* @return

*/

public Book getById(Integer id);

/**

* 查询全部

* @return

*/

public ListgetAll();

}

package com.itheima.service.impl;

import com.itheima.dao.BookDao;

import com.itheima.domain.Book;

import com.itheima.service.BookService;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service

public class BookServiceImpl implements BookService {

@Autowired

private BookDao bookDao;

@Override

public boolean save(Book book) {

bookDao.save(book);

return true;

}

@Override

public boolean update(Book book) {

bookDao.update(book);

return true;

}

@Override

public boolean delete(Integer id) {

bookDao.delete(id);

return true;

}

@Override

public Book getById(Integer id) {

return bookDao.getById(id);

}

@Override

public ListgetAll() {

return bookDao.getAll();

}

}

3.5 编写Controller类

package com.itheima.controller;

import com.itheima.domain.Book;

import com.itheima.service.BookService;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController

@RequestMapping("/books")

public class BookController {

@Autowired

private BookService bookService;

@PostMapping

public boolean save(@RequestBody Book book){

return bookService.save(book);

}

@PutMapping

public boolean update(@RequestBody Book book){

return bookService.update(book);

}

@DeleteMapping("/{id}")

public boolean delete(@PathVariable Integer id){

return bookService.delete(id);

}

@GetMapping("/{id}")

public Book getById(@PathVariable Integer id){

return bookService.getById(id);

}

@GetMapping

public ListgetAll(){

return bookService.getAll();

}

}

3.6 总体架构

4. 单元测试

4.1 新建测试类

@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration(classes = SpringConfig.class)

public class BookServiceTest {

}

4.2 注入Service类

@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration(classes = SpringConfig.class)

public class BookServiceTest {

@Autowired

private BookService bookService;

}

4.3 新增测试方法

@Test

public void testSave(){

Book book = new Book(null, "计算机理论", "Java第五版", "Java入门到精通");

boolean save = bookService.save(book);

System.out.println(save);

}

4.4 修改测试方法

@Test

public void testUpdate(){

Book book = new Book(18, "计算机理论", "Java第五版666", "Java入门到精通");

boolean update = bookService.update(book);

System.out.println(update);

}

4.5 删除测试方法

@Test

public void testDelete(){

System.out.println(bookService.delete(18));

}

4.6 查询单个测试方法

@Test

public void testGetById(){

Book book = bookService.getById(1);

System.out.println(book);

}

4.7 查询所有测试方法

@Test

public void testGetAll(){

ListbookList = bookService.getAll();

for(Book book : bookList){

System.out.println(book);

}

}

5. PostMan测试

启动Tomcat

5.1 新增

查看数据库:

5.2 修改

查看数据库:

5.3 删除

5.4 查询单个

5.5 查询所有

6 总结

SMM整合可以分成如下三块:

整合配置

添加依赖(相关依赖)数据库资源文件jdbc.pripertiesJdbcConfig配置类MyBatisConfig配置类SpringConfig配置类SpringMVC配置类Web项目入口配置类(重点)

功能模块的开发(从下到上进行开发)

数据库以及表数据库每张表对应的实体类数据层编写:Dao/Mapper层业务层编写:Service层表现层编写:Controller层

测试

单元测试:测试Service或者Dao层连接数据接口是否正确;PostMan:测试Controller层接口是否正确;

注意:如果在做的过程中遇到问题,可以参考文章:框架(Spring、SpringMvc、MyBatis)学习过程中遇到的问题以及解决方式汇总(持续更新~~~), 查看是否有相应的解决方案。

标签: 拼多多助力网站平台 赚钱项目 拼多多助力网 首码项目 手赚APP
拼多多助力营销技巧