欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

详解mall整合SpringBoot+MyBatis搭建基本骨架

程序员文章站 2023-11-21 17:34:22
springboot实战电商项目mall(20k+star)地址: 摘要 本文主要讲解mall整合springboot+mybatis搭建基本骨架,以商品品牌为例实现基...
springboot实战电商项目mall(20k+star)地址:

摘要

本文主要讲解mall整合springboot+mybatis搭建基本骨架,以商品品牌为例实现基本的crud操作及通过pagehelper实现分页查询。

mysql数据库环境搭建

下载并安装mysql5.7版本,下载地址:

设置数据库帐号密码:root root

下载并安装客户端连接工具navicat,下载地址:

创建数据库mall导入

mall的数据库脚本,脚本地址:

项目使用框架介绍

springboot

springboot可以让你快速构建基于spring的web应用程序,内置多种web容器(如tomcat),通过启动入口程序的main函数即可运行。

pagerhelper

mybatis分页插件,简单的几行代码就能实现分页,在与springboot整合时,只要整合了pagerhelper就自动整合了mybatis。
pagehelper.startpage(pagenum, pagesize);
//之后进行查询操作将自动进行分页
list<pmsbrand> brandlist = brandmapper.selectbyexample(new pmsbrandexample());
//通过构造pageinfo对象获取分页信息,如当前页码,总页数,总条数
pageinfo<pmsbrand> pageinfo = new pageinfo<pmsbrand>(list);

druid

alibaba开源的数据库连接池,号称java语言中最好的数据库连接池。

mybatis generator

mybatis的代码生成器,可以根据数据库生成model、mapper.xml、mapper接口和example,通常情况下的单表查询不用再手写mapper。

项目搭建

使用idea初始化一个springboot项目

详解mall整合SpringBoot+MyBatis搭建基本骨架

添加项目依赖

在pom.xml中添加相关依赖。
<parent>
    <groupid>org.springframework.boot</groupid>
    <artifactid>spring-boot-starter-parent</artifactid>
    <version>2.1.3.release</version>
    <relativepath/> <!-- lookup parent from repository -->
  </parent>
  <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>

修改springboot配置文件

在application.yml中添加数据源配置和mybatis的mapper.xml的路径配置。
server:
 port: 8080

spring:
 datasource:
  url: jdbc:mysql://localhost:3306/mall?useunicode=true&characterencoding=utf-8&servertimezone=asia/shanghai
  username: root
  password: root

mybatis:
 mapper-locations:
  - classpath:mapper/*.xml
  - classpath*:com/**/mapper/*.xml

项目结构说明

详解mall整合SpringBoot+MyBatis搭建基本骨架

mybatis generator 配置文件

配置数据库连接,mybatis generator生成model、mapper接口及mapper.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.macro.mall.tiny.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.macro.mall.tiny.mbg.model" targetproject="mall-tiny-01\src\main\java"/>
    <!--指定生成mapper.xml的路径-->
    <sqlmapgenerator targetpackage="com.macro.mall.tiny.mbg.mapper" targetproject="mall-tiny-01\src\main\resources"/>
    <!--指定生成mapper接口的的路径-->
    <javaclientgenerator type="xmlmapper" targetpackage="com.macro.mall.tiny.mbg.mapper"
               targetproject="mall-tiny-01\src\main\java"/>
    <!--生成全部表tablename设为%-->
    <table tablename="pms_brand">
      <generatedkey column="id" sqlstatement="mysql" identity="true"/>
    </table>
  </context>
</generatorconfiguration>

运行generator的main函数生成代码

package com.macro.mall.tiny.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 macro 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);
    }
  }
}

添加mybatis的java配置

用于配置需要动态生成的mapper接口的路径
package com.macro.mall.tiny.config;

import org.mybatis.spring.annotation.mapperscan;
import org.springframework.context.annotation.configuration;

/**
 * mybatis配置类
 * created by macro on 2019/4/8.
 */
@configuration
@mapperscan("com.macro.mall.tiny.mbg.mapper")
public class mybatisconfig {
}

实现controller中的接口

实现pmsbrand表中的添加、修改、删除及分页查询接口。
package com.macro.mall.tiny.controller;

import com.macro.mall.tiny.common.api.commonpage;
import com.macro.mall.tiny.common.api.commonresult;
import com.macro.mall.tiny.mbg.model.pmsbrand;
import com.macro.mall.tiny.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.validation.bindingresult;
import org.springframework.web.bind.annotation.*;

import java.util.list;


/**
 * 品牌管理controller
 * created by macro on 2019/4/19.
 */
@controller
@requestmapping("/brand")
public class pmsbrandcontroller {
  @autowired
  private pmsbrandservice demoservice;

  private static final logger logger = loggerfactory.getlogger(pmsbrandcontroller.class);

  @requestmapping(value = "listall", method = requestmethod.get)
  @responsebody
  public commonresult<list<pmsbrand>> getbrandlist() {
    return commonresult.success(demoservice.listallbrand());
  }

  @requestmapping(value = "/create", method = requestmethod.post)
  @responsebody
  public commonresult createbrand(@requestbody pmsbrand pmsbrand) {
    commonresult commonresult;
    int count = demoservice.createbrand(pmsbrand);
    if (count == 1) {
      commonresult = commonresult.success(pmsbrand);
      logger.debug("createbrand success:{}", pmsbrand);
    } else {
      commonresult = commonresult.failed("操作失败");
      logger.debug("createbrand failed:{}", pmsbrand);
    }
    return commonresult;
  }

  @requestmapping(value = "/update/{id}", method = requestmethod.post)
  @responsebody
  public commonresult updatebrand(@pathvariable("id") long id, @requestbody pmsbrand pmsbranddto, bindingresult result) {
    commonresult commonresult;
    int count = demoservice.updatebrand(id, pmsbranddto);
    if (count == 1) {
      commonresult = commonresult.success(pmsbranddto);
      logger.debug("updatebrand success:{}", pmsbranddto);
    } else {
      commonresult = commonresult.failed("操作失败");
      logger.debug("updatebrand failed:{}", pmsbranddto);
    }
    return commonresult;
  }

  @requestmapping(value = "/delete/{id}", method = requestmethod.get)
  @responsebody
  public commonresult deletebrand(@pathvariable("id") long id) {
    int count = demoservice.deletebrand(id);
    if (count == 1) {
      logger.debug("deletebrand success :id={}", id);
      return commonresult.success(null);
    } else {
      logger.debug("deletebrand failed :id={}", id);
      return commonresult.failed("操作失败");
    }
  }

  @requestmapping(value = "/list", method = requestmethod.get)
  @responsebody
  public commonresult<commonpage<pmsbrand>> listbrand(@requestparam(value = "pagenum", defaultvalue = "1") integer pagenum,
                            @requestparam(value = "pagesize", defaultvalue = "3") integer pagesize) {
    list<pmsbrand> brandlist = demoservice.listbrand(pagenum, pagesize);
    return commonresult.success(commonpage.restpage(brandlist));
  }

  @requestmapping(value = "/{id}", method = requestmethod.get)
  @responsebody
  public commonresult<pmsbrand> brand(@pathvariable("id") long id) {
    return commonresult.success(demoservice.getbrand(id));
  }
}

添加service接口

package com.macro.mall.tiny.service;


import com.macro.mall.tiny.mbg.model.pmsbrand;

import java.util.list;

/**
 * pmsbrandservice
 * created by macro on 2019/4/19.
 */
public interface pmsbrandservice {
  list<pmsbrand> listallbrand();

  int createbrand(pmsbrand brand);

  int updatebrand(long id, pmsbrand brand);

  int deletebrand(long id);

  list<pmsbrand> listbrand(int pagenum, int pagesize);

  pmsbrand getbrand(long id);
}

实现service接口

package com.macro.mall.tiny.service.impl;

import com.github.pagehelper.pagehelper;
import com.macro.mall.tiny.mbg.mapper.pmsbrandmapper;
import com.macro.mall.tiny.mbg.model.pmsbrand;
import com.macro.mall.tiny.mbg.model.pmsbrandexample;
import com.macro.mall.tiny.service.pmsbrandservice;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.stereotype.service;

import java.util.list;

/**
 * pmsbrandservice实现类
 * created by macro on 2019/4/19.
 */
@service
public class pmsbrandserviceimpl implements pmsbrandservice {
  @autowired
  private pmsbrandmapper brandmapper;

  @override
  public list<pmsbrand> listallbrand() {
    return brandmapper.selectbyexample(new pmsbrandexample());
  }

  @override
  public int createbrand(pmsbrand brand) {
    return brandmapper.insertselective(brand);
  }

  @override
  public int updatebrand(long id, pmsbrand brand) {
    brand.setid(id);
    return brandmapper.updatebyprimarykeyselective(brand);
  }

  @override
  public int deletebrand(long id) {
    return brandmapper.deletebyprimarykey(id);
  }

  @override
  public list<pmsbrand> listbrand(int pagenum, int pagesize) {
    pagehelper.startpage(pagenum, pagesize);
    return brandmapper.selectbyexample(new pmsbrandexample());
  }

  @override
  public pmsbrand getbrand(long id) {
    return brandmapper.selectbyprimarykey(id);
  }
}

项目源码地址

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。