电商项目实战——SpringBoot+MyBatis搭建基本骨架

Posted 不浪小生

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了电商项目实战——SpringBoot+MyBatis搭建基本骨架相关的知识,希望对你有一定的参考价值。

一、前言

  开发一个项目,最开始的一步就是搭建一个开发环境,也就是需要选择什么框架进行项目的开发,本次搭建一个springboot+mybatis的开发框架,通过实现商品品牌的增删改查,测试搭建是否成功。

二、框架介绍

  本次使用四个框架分别是:SpringBoot(SpringBoot可以快速搭建web应用程序,内置多种Web容器,如Tomcat),Mybatis + PagerHelper(mybatis自带的分页插件),Druid(阿里巴巴开源的数据库连接池),Mybatis Generator(Mybatis的代码生成器,可以根据数据库表自动生成model、mapper.java、mapper.xml、example)。

三、内容

  1、新建一个springboot的module

  

  项目目录组成

  

 

 

  2、添加pom文件的依赖

<dependencies>
        <!--SpringBoot通用依赖模块-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--MyBatis分页插件-->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.10</version>
        </dependency>
        <!--集成druid连接池-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>
        <!-- MyBatis 生成器 -->
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.3</version>
        </dependency>
        <!--mysql数据库驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.15</version>
        </dependency>
    </dependencies>
  
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>

<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
 

  3、修改springboot的配置文件

server:
  port: 10077
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
    username: root
    password: root
mybatis:
  mapper-locations:
  classpath: com/zzb/test/admin/mapper/*.xml

  4、mybatis自动生成代码

  mysql新建品牌表:pms_brand

  

 

 

  generator.properties连接数据库配置文件

jdbc.driverClass=com.mysql.cj.jdbc.Driver

jdbc.connectionURL=jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
jdbc.userId=root

jdbc.password=root

  生成代码的generator.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>

<!
DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <properties resource="generator.properties"/> <context id="MySqlContext" targetRuntime="MyBatis3" defaultModelType="flat"> <property name="beginningDelimiter" value="`"/> <property name="endingDelimiter" value="`"/> <property name="javaFileEncoding" value="UTF-8"/> <!-- 为模型生成序列化方法--> <plugin type="org.mybatis.generator.plugins.SerializablePlugin"/> <!-- 为生成的Java模型创建一个toString方法 --> <plugin type="org.mybatis.generator.plugins.ToStringPlugin"/> <!--可以自定义生成model的代码注释--> <commentGenerator type="com.zzb.test.admin.mbg.CommentGenerator"> <!-- 是否去除自动生成的注释 true:是 : false:否 --> <property name="suppressAllComments" value="true"/> <property name="suppressDate" value="true"/> <property name="addRemarkComments" value="true"/> </commentGenerator> <!--配置数据库连接--> <jdbcConnection driverClass="${jdbc.driverClass}" connectionURL="${jdbc.connectionURL}" userId="${jdbc.userId}" password="${jdbc.password}"> <!--解决mysql驱动升级到8.0后不生成指定数据库代码的问题--> <property name="nullCatalogMeansCurrent" value="true"/> </jdbcConnection> <!--指定生成model的路径--> <javaModelGenerator targetPackage="com.zzb.test.admin.mbg.model" targetProject="shoptest\\admin\\src\\main\\java"/> <!--指定生成mapper接口的路径--> <sqlMapGenerator targetPackage="com.zzb.test.admin.mbg.mapper" targetProject="shoptest\\admin\\src\\main\\java"/> <!--指定生成mapper.xml的路径--> <javaClientGenerator type="XMLMAPPER" targetPackage="com.zzb.test.admin.mbg.mapper" targetProject="shoptest\\admin\\src\\main\\java"/> <!--生成全部表tableName设为%--> <table tableName="pms_brand"></table> </context> </generatorConfiguration>

  生成代码后自动添加注释的配置类CommentGenerator

package com.zzb.test.admin.mbg;

import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.internal.DefaultCommentGenerator;
import org.mybatis.generator.internal.util.StringUtility;

import java.util.Properties;

/**
 * 自定义注释生成器
 * Created by zzb on 2018/4/26.
 */
public class CommentGenerator extends DefaultCommentGenerator {
    private boolean addRemarkComments = false;

    /**
     * 设置用户配置的参数
     */
    @Override
    public void addConfigurationProperties(Properties properties) {
        super.addConfigurationProperties(properties);
        this.addRemarkComments = StringUtility.isTrue(properties.getProperty("addRemarkComments"));
    }

    /**
     * 给字段添加注释
     */
    @Override
    public void addFieldComment(Field field, IntrospectedTable introspectedTable,
                                IntrospectedColumn introspectedColumn) {
        String remarks = introspectedColumn.getRemarks();
        //根据参数和备注信息判断是否添加备注信息
        if (addRemarkComments && StringUtility.stringHasValue(remarks)) {
            addFieldJavaDoc(field, remarks);
        }
    }

    /**
     * 给model的字段添加注释
     */
    private void addFieldJavaDoc(Field field, String remarks) {
        //文档注释开始
        field.addJavaDocLine("/**");
        //获取数据库字段的备注信息
        String[] remarkLines = remarks.split(System.getProperty("line.separator"));
        for (String remarkLine : remarkLines) {
            field.addJavaDocLine(" * " + remarkLine);
        }
        addJavadocTag(field, false);
        field.addJavaDocLine(" */");
    }

}

  读取generatorConfig.xml文件的启动类Generator

package com.zzb.test.admin.mbg;

import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 用于生产MBG的代码
 * Created by zzb on 2018/4/26.
 */
public class Generator {
    public static void main(String[] args) throws Exception {
        //MBG 执行过程中的警告信息
        List<String> warnings = new ArrayList<String>();
        //当生成的代码重复时,覆盖原代码
        boolean overwrite = true;
        //读取我们的 MBG 配置文件
        InputStream is = Generator.class.getResourceAsStream("/generatorConfig.xml");
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(is);
        is.close();

        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        //创建 MBG
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
        //执行生成代码
        myBatisGenerator.generate(null);
        //输出警告信息
        for (String warning : warnings) {
            System.out.println(warning);
        }
    }
}

  5、运行自动生成代码的启动类Generator

  

 

 

 

  6、配置mybatis的映射路径,在配置类包下新建一个mybatis的配置类

package com.zzb.test.admin.config;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Configuration;

/**
 * Created by zzb on 2019/11/15 9:36
 */
@Configuration
@MapperScan("com.zzb.test.admin.mbg.mapper")
public class MybatisConfig {
}

  7、新建通用返回结果

  在通用工具类包下新建结果枚举类ResultCode

package com.zzb.test.admin.common;

/**
 * 枚举返回结果
 * Created by zzb on 2019/11/15 11:39
 */
public enum ResultCode {
    SUCCESS(200, "操作成功"),
    FAILED(500, "操作失败"),
    FORBIDDEN(403, "没有相关权限");

    private long code;
    private String message;

    private ResultCode(long code,String message){
        this.code = code;
        this.message = message;
    }

    public long getCode() {
        return code;
    }

    public void setCode(long code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

  在通用工具类包下新建结果返回类

package com.zzb.test.admin.common;

/**
 * 通用的返回对象
 * Created by zzb on 2019/11/15 11:47
 */
public class CommonResult<T> {

    private long code;
    private String message;
    private T data;

    protected CommonResult(){}

    protected CommonResult(long code,String message,T data){
        this.code = code;
        this.message = message;
        this.data = data;
    }

    /**
     * 返回成功结果
     * @param data
     * @param <T>
     * @return
     */
    public static <T> CommonResult<T> success(T data){
        return new CommonResult<T>(ResultCode.SUCCESS.getCode(),ResultCode.SUCCESS.getMessage(),data);
    }

    /**
     * 返回成功结果,自定义信息
     * @param data
     * @param <T>
     * @return
     */
    public static <T> CommonResult<T> success(T data,String message){
        return new CommonResult<T>(ResultCode.SUCCESS.getCode(),message,data);
    }

    /**
     * 返回失败结果
     * @param <T>
     * @return
     */
    public static <T> CommonResult<T> failed(){
        return new CommonResult<T>(ResultCode.FAILED.getCode(),ResultCode.FAILED.getMessage(),null);
    }

    /**
     * 返回失败结果,自定义信息
     * @param <T>
     * @return
     */
    public static <T> CommonResult<T> failed(String message){
        return new CommonResult<T>(ResultCode.FAILED.getCode(),message,null);
    }

    /**
     * 未授权返回结果
     * @param <T>
     * @return
     */
    public static <T> CommonResult<T> forbbiden(){
        return new CommonResult<T>(ResultCode.FORBIDDEN.getCode(),ResultCode.FAILED.getMessage(),null);
    }

    /**
     * 未授权返回结果,自定义信息
     * @param <T>
     * @return
     */
    public static <T> CommonResult<T> forbbiden(String message){
        return new CommonResult<T>(ResultCode.FORBIDDEN.getCode(),message,null);
    }

    public long getCode() {
        return code;
    }

    public void setCode(long code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}

  在通用工具类包下新建分页封装类

package com.zzb.test.admin.common;

import com.github.pagehelper.PageInfo;

import java.util.List;

/**
 * mybatis分页封装
 * Created by zzb on 2019/11/15 12:27
 */
public class CommonPage<T> {
    private Integer pageNum;
    private Integer pageSize;
    private Integer totalPage;
    private Long total;
    private List<T> list;

    public static <T> CommonPage<T> restPage(List<T> list){
        CommonPage<T> result = new CommonPage<>();
        PageInfo<T> pageInfo = new PageInfo<>(list);
        result.setPageNum(pageInfo.getPageNum());
        result.setPageSize(pageInfo.getPageSize());
        result.setTotal(pageInfo.getTotal());
        result.setList(pageInfo.getList());
        return result;
        }

    public Integer getPageNum() {
        return pageNum;
    }

    public void setPageNum(Integer pageNum) {
        this.pageNum = pageNum;
    }

    public Integer getPageSize() {
        return pageSize;
    }

    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }

    public Integer getTotalPage() {
        return totalPage;
    }

    public void setTotalPage(Integer totalPage) {
        this.totalPage = totalPage;
    }

    public Long getTotal() {
        return total;
    }

    public void setTotal(Long total) {
        this.total = total;
    }

    public List<T> getList() {
        return list;
    }

    public void setList(List<T> list) {
        this.list = list;
    }
}

  8、实现商品品牌表的操作

  在控制器包下新建controller类

package com.zzb.test.admin.controller;

import com.zzb.test.admin.common.CommonPage;
import com.zzb.test.admin.common.CommonResult;
import com.zzb.test.admin.mbg.model.PmsBrand;
import com.zzb.test.admin.service.PmsBrandService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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 java.util.List;

/**
 * 品牌管理Controller
 * Created by zzb on 2019/11/15 10:28
 */
@Controller
public class PmsBrandController {

    @Autowired
    private PmsBrandService pmsBrandService;

    private static final Logger logger = LoggerFactory.getLogger(PmsBrandController.class);

    @RequestMapping(value = "/admin/brand/getList", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<CommonPage<PmsBrand>> getList(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                           @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize){
        List<PmsBrand> list = pmsBrandService.getList(pageNum,pageSize);
        logger.info("分页查询所有品牌==》" + list);
        return CommonResult.success(CommonPage.restPage(list));
    }

    @RequestMapping(value = "/admin/brand/insert", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult insert(PmsBrand pmsBrand){
        int count = pmsBrandService.insert(pmsBrand);
        logger.info("添加品牌==》" + count);
        if (count>0) {
            return CommonResult.success("添加品牌成功");
        }
        return CommonResult.failed();
    }

    @RequestMapping(value = "/admin/brand/delete", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult delete(Long id){
        int count = pmsBrandService.delete(id);
        logger.info("删除品牌==》" + count);
        if (count>0) {
            return CommonResult.success("删除品牌成功");
        }
        return CommonResult.failed();
    }

    @RequestMapping(value = "/admin/brand/update", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult update(PmsBrand pmsBrand){
        int count = pmsBrandService.update(pmsBrand);
        logger.info("更新品牌==》" + count);
        if (count>0) {
            return CommonResult.success("更新品牌成功");
        }
        return CommonResult.failed();
    }

}

 

  在业务实现包中新建service

package com.zzb.test.admin.service;

import com.zzb.test.admin.mbg.model.PmsBrand;

import java.util.List;

/**
 * 品牌管理Service
 * Created by zzb on 2019/11/15 10:38
 */
public interface PmsBrandService {

    List<PmsBrand> getList(Integer pageNum,Integer pageSize);

    int insert(PmsBrand pmsBrand);

    int delete(Long id);

    int update(PmsBrand pmsBrand);
}

  在业务实现包中新建其实现类

package com.zzb.test.admin.service.impl;

import com.github.pagehelper.PageHelper;
import com.zzb.test.admin.mbg.mapper.PmsBrandMapper;
import com.zzb.test.admin.mbg.model.PmsBrand;
import com.zzb.test.admin.service.PmsBrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * PmsBrandService的实现类
 * Created by zzb on 2019/11/15 10:40
 */
@Service
@Transactional
public class PmsBrandServiceImpl implements PmsBrandService {

    @Autowired
    private PmsBrandMapper pmsBrandMapper;

    @Override
    public List<PmsBrand> getList(Integer pageNum,Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        return pmsBrandMapper.selectByExample(null);
    }

    @Override
    public int insert(PmsBrand pmsBrand) {
        return pmsBrandMapper.insert(pmsBrand);
    }

    @Override
    public int delete(Long id) {
        return pmsBrandMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int update(PmsBrand pmsBrand) {
        return pmsBrandMapper.updateByPrimaryKeySelective(pmsBrand);
    }
}

 

  8、测试接口

 

 

 

  项目github地址:https://github.com/18372561381/shoptest

以上是关于电商项目实战——SpringBoot+MyBatis搭建基本骨架的主要内容,如果未能解决你的问题,请参考以下文章

JS的防抖与节流 -- springboot实战电商项目mall4j

SpringBoot电商项目实战 — Redis实现分布式锁

SpringBoot电商项目实战 — ElasticSearch接入实现

SpringBoot电商项目实战 — Zookeeper的分布式锁实现

构建SpringBoot,SpringCloud微服务架构分布式电商项目实战

SpringBoot电商项目实战 — 前后端分离后的优雅部署及Nginx部署实现