SpringBoot框架之整合Mybatis、SpringMVC(“S“SM整合)

在上一篇博客 SpringBoot框架之创建第一个项目(两种方式)演示了如何创建使用SpringBootSpringMVC框架的项目,在此篇博客将进一步演示整合Mybatis框架,也就是SpringSpringMVCMybatis三大框架的整合(SpringBoot框架的实质是提供更简洁的使用Spring的方式)。

一、项目搭建

在这里插入图片描述

1、使用Spring Initializr方式创建项目

在这里插入图片描述

2、设置项目名、jdk环境相配置

在这里插入图片描述

3、勾选web(SpringMVC)

在这里插入图片描述

4、勾选Mybatis

在这里插入图片描述

5、设置项目名

在这里插入图片描述
第一次需要下载较多的资源文件,稍作等待。
在这里插入图片描述

二、编写Java代码

1、建库建表

# 创建spring_boot_ssm数据库
DROP DATABASE IF EXISTS `spring_boot_ssm`;
CREATE DATABASE `spring_boot_ssm`;
# 选中spring_boot_ssm数据库
USE `spring_boot_ssm`;
# 创建t_product表
DROP TABLE IF EXISTS `t_product`;
CREATE TABLE `t_product` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(32) DEFAULT NULL COMMENT '产品名称',
  `price` double DEFAULT NULL COMMENT '产品价格',
  `number` int(11) DEFAULT NULL COMMENT '库存数量',
  `info` varchar(200) DEFAULT NULL COMMENT '产品简介',
  `picture_path` varchar(100) DEFAULT NULL COMMENT '产品照片路径',
  `created_time` date DEFAULT NULL COMMENT '产品创建时间',
  PRIMARY KEY (`id`)
);
# 往t_product表中插入数据
INSERT INTO `t_product` VALUES (1, '电脑', 5000.5, 50, '性能吊打苹果!', NULL, '2020-01-30');
INSERT INTO `t_product` VALUES (2, '手机', 2000.9, 20, '性价比第一!', NULL, '2020-01-30');
INSERT INTO `t_product` VALUES (3, '平板', 32000.9, 40, '性能宇宙第一!', NULL, '2020-01-30');

在这里插入图片描述

2、编写Product实体类

在这里插入图片描述

package cn.hestyle.spring_boot_ssm.entity;

import java.io.Serializable;
import java.util.Date;

/**
 * description: Product实体类
 *
 * @author hestyle
 * @version 1.0
 * @className ssm_demo_01->Product
 * @date 2020-01-30 10:30
 **/
public class Product implements Serializable {
    private Integer id;
    /**商品名*/
    private String name;
    /**商品价格*/
    private Double price;
    /**商品库存数量*/
    private Integer number;
    /**商品简介*/
    private String info;
    /**商品照片路径*/
    private String picturePath;
    /**商品创建时间*/
    private Date createdTime;

    public Product() {
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    public Integer getNumber() {
        return number;
    }

    public void setNumber(Integer number) {
        this.number = number;
    }

    public String getInfo() {
        return info;
    }

    public void setInfo(String info) {
        this.info = info;
    }

    public String getPicturePath() {
        return picturePath;
    }

    public void setPicturePath(String picturePath) {
        this.picturePath = picturePath;
    }

    public Date getCreatedTime() {
        return createdTime;
    }

    public void setCreatedTime(Date createdTime) {
        this.createdTime = createdTime;
    }

    @Override
    public String toString() {
        return "Product{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", price=" + price +
                ", number=" + number +
                ", info='" + info + '\'' +
                ", picturePath='" + picturePath + '\'' +
                ", createdTime=" + createdTime +
                '}';
    }
}

3、编写mapper(也称dao层)

新增ProductMapper接口类,并且添加@Mapper注解
在这里插入图片描述

package cn.hestyle.spring_boot_ssm.mapper;

import cn.hestyle.spring_boot_ssm.entity.Product;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

/**
 * description: ProductMapper接口类,相当于IProductDao接口类
 *
 * @author hestyle
 * @version 1.0
 * @className ssm_demo_01->ProductMapper
 * @date 2020-01-30 10:36
 **/
@Mapper
public interface ProductMapper {
    /**
     * 保存product
     * @param product 待保存的product实体对象
     * @return 受影响的行数
     */
    public Integer save(Product product);

    /**
     * 更新product
     * @param product 待更新的product实体对象
     * @return 受影响的行数
     */
    public Integer update(Product product);

    /**
     * 通过id删除product
     * @param id 待删除的product实体对象id
     * @return 受影响的行数
     */
    public Integer deleteById(Integer id);

    /**
     * 通过id查找product
     * @param id 待删除的product实体对象id
     * @return 查找到的实体对象
     */
    public Product findById(Integer id);

    /**
     * 查找所有product
     * @return Product list
     */
    public List<Product> findAll();
}

src/main/resources目录下新增mappers目录
在这里插入图片描述
新增ProductMapper.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">
<!--
	namespace:命名空间,它的作用就是对SQL进行分类化管理,可以理解为SQL隔离
	注意:使用mapper代理开发时,namespace有特殊且重要的作用
 -->
<mapper namespace="cn.hestyle.spring_boot_ssm.mapper.ProductMapper">
	<!--
	保存product对象, public Integer save(Product product);
        [id]:statement的id,要求在命名空间内唯一
        keyProperty="id" useGeneratedKeys="true"用于设置自动增长标识(id字段自动增长)
        [parameterType]:入参的java类型
     -->
	<insert id="save" keyProperty="id" useGeneratedKeys="true" parameterType="cn.hestyle.spring_boot_ssm.entity.Product">
		INSERT INTO `t_product`(
			`name`, `price`, `number`, `info`, `picture_path`, `created_time`
		) VALUES (
			#{name},#{price},#{number},#{info},#{picturePath},#{createdTime}
		)
	</insert>

	<!--
	更新product对象, public Integer update(Product product);
        注意created_time不用更新,可以在表中增加一个modify_time字段,trim的作用是删除最后一个逗号
     -->
	<update id="update" parameterType="cn.hestyle.spring_boot_ssm.entity.Product">
		UPDATE `t_product`
		<trim prefix="set" suffixOverrides=",">
			<if test="name != null">
				`name` = #{name},
			</if>
			<if test="price != null">
				`price` = #{price},
			</if>
			<if test="number != null">
				`number` = #{number},
			</if>
			<if test="info != null">
				`info` = #{info},
			</if>
			<if test="picturePath != null">
				`picture_path` = #{picturePath},
			</if>
		</trim>
		WHERE id = #{id}
	</update>

	<!--
	通过id删除product对象,public Integer deleteById(Integer id);
        注意这里可以不用真的删除,可以在表中增加一个is_del字段记录是否删除
     -->
	<delete id="deleteById" parameterType="java.lang.Integer">
		DELETE FROM `t_product`
		WHERE id = #{id}
	</delete>

    <!--
    通过id查找Product表, public Product findById(Integer id);
        由于表中的picture_path、created_time字段与Product实体类中的picturePath、createdTime属性不对应,所以需要手动指定映射关系
     -->
    <select id="findById" parameterType="java.lang.Integer" resultType="cn.hestyle.spring_boot_ssm.entity.Product">
		SELECT `id`, `name`, `price`, `number`, `info`, `picture_path` picturePath, `created_time` createdTime
		FROM `t_product`
		WHERE id = #{id}
	</select>

	<!--
    查找product表所有记录,public List<Product> findAll();
        由于表中的picture_path、created_time字段与Product实体类中的picturePath、createdTime属性不对应,所以需要手动指定映射关系
        虽然指定的返回类型是Product,不过这里可能会查到多条数据,因此会自动转化成list
     -->
	<select id="findAll" resultType="cn.hestyle.spring_boot_ssm.entity.Product">
		SELECT `id`, `name`, `price`, `number`, `info`, `picture_path` picturePath, `created_time` createdTime
		FROM `t_product`
	</select>
</mapper>

4、编写service层

新增IProductService接口
在这里插入图片描述

package cn.hestyle.spring_boot_ssm.service;


import cn.hestyle.spring_boot_ssm.entity.Product;

import java.util.List;

/**
 * description: IProductService接口类
 *
 * @author hestyle
 * @version 1.0
 * @className ssm_demo_01->IProductService
 * @date 2020-01-30 11:10
 **/
public interface IProductService {
    /**
     * 保存product
     * @param product 待保存的product实体对象
     * @return 受影响的行数
     */
    public Integer save(Product product);

    /**
     * 更新product
     * @param product 待更新的product实体对象
     * @return 受影响的行数
     */
    public Integer update(Product product);

    /**
     * 通过id删除product
     * @param id 待删除的product实体对象id
     * @return 受影响的行数
     */
    public Integer deleteById(Integer id);

    /**
     * 通过id查找product
     * @param id 待删除的product实体对象id
     * @return 查找到的实体对象
     */
    public Product findById(Integer id);

    /**
     * 查找所有product
     * @return Product list
     */
    public List<Product> findAll();
}

新增ProductServiceImpl实现类,并添加@Service注解
在这里插入图片描述

package cn.hestyle.spring_boot_ssm.service.impl;


import cn.hestyle.spring_boot_ssm.entity.Product;
import cn.hestyle.spring_boot_ssm.mapper.ProductMapper;
import cn.hestyle.spring_boot_ssm.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * description: ProductServiceImpl实现类
 *
 * @author hestyle
 * @version 1.0
 * @className ssm_demo_01->ProductServiceImpl
 * @date 2020-01-30 11:13
 **/
@Service
@Transactional
public class ProductServiceImpl implements IProductService {
    @Autowired
    private ProductMapper productMapper;

    @Override
    public Integer save(Product product) {
        return productMapper.save(product);
    }

    @Override
    public Integer update(Product product) {
        return productMapper.update(product);
    }

    @Override
    public Integer deleteById(Integer id) {
        return productMapper.deleteById(id);
    }

    @Override
    public Product findById(Integer id) {
        return productMapper.findById(id);
    }

    @Override
    public List<Product> findAll() {
        return productMapper.findAll();
    }
}

5、编写Controller层

新增ProductController控制器类,并设置@Controller注解
在这里插入图片描述

package cn.hestyle.spring_boot_ssm.web.controller;

import cn.hestyle.spring_boot_ssm.entity.Product;
import cn.hestyle.spring_boot_ssm.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * description: Product控制器
 *
 * @author hestyle
 * @version 1.0
 * @className spring_boot_ssm->ProductController
 * @date 2020-02-07 18:43
 **/
@Controller
@RequestMapping("product")
public class ProductController {
    @Autowired
    private IProductService productService;

    @GetMapping("findAll")
    @ResponseBody
    public List<Product> findAll() {
        return productService.findAll();
    }
}

三、编写配置文件

application.properties文件中添加MySQL数据库、Mybatis映射文件路径配置
在这里插入图片描述

# MySQL数据库相关,驱动、数据库url、访问数据库的用户名、密码
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost/spring_boot_ssm?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=123456

# spring集成Mybatis环境
# 加载Mybatis映射文件
mybatis.mapper-locations=classpath:mappers/*Mapper.xml

四、启动项目

在这里插入图片描述
控制台输出信息:
在这里插入图片描述
浏览器访问http://localhost:8080/product/findAll
在这里插入图片描述
成功获取到了数据库中的数据。

以上就是SpringBoot框架之整合MybatisSpringMVC(“S“SM整合)的主要内容,可以看出SpringBoot整合SSM三大框架比起手动整合方便了很多,这也正是SpringBoot的优势所在。

发布了976 篇原创文章 · 获赞 230 · 访问量 20万+

猜你喜欢

转载自blog.csdn.net/qq_41855420/article/details/104212291