码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2019-11-15 12:17:06      阅读:89      评论:0      收藏:0      [点我收藏+]

标签:指定   数据库连接池   update   nts   mic   llb   sele   新建   lca   

一、前言

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

二、框架介绍

  本次使用四个框架分别是:SpringBoot(SpringBoot可以快速搭建web应用程序,内置多种Web容器,如Tomcat),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自动生成代码

  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="admin\src\main\java"/> <!--指定生成mapper接口的路径--> <sqlMapGenerator targetPackage="com.zzb.test.admin.mbg.mapper" targetProject="admin\src\main\java"/> <!--指定生成mapper.xml的路径--> <javaClientGenerator type="XMLMAPPER" targetPackage="com.zzb.test.admin.mbg.mapper" targetProject="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、实现商品品牌表的操作

  在控制器包下新建controller类

package com.zzb.test.admin.controller;

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.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 List<PmsBrand> getList(){
        List<PmsBrand> list = pmsBrandService.getList();
        logger.info("查询所有品牌==》" + list);
        return list;
    }

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

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

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

}

  在业务实现包中新建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();

    int insert(PmsBrand pmsBrand);

    int delete(Long id);

    int update(PmsBrand pmsBrand);
}

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

  

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

import com.zzb.test.admin.mbg.mapper.PmsBrandMapper;
import com.zzb.test.admin.mbg.model.PmsBrand;
import com.zzb.test.admin.mbg.model.PmsBrandExample;
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() {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、测试接口

  技术图片

 

 

  

 

  

  

 

 

 

  

 

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

标签:指定   数据库连接池   update   nts   mic   llb   sele   新建   lca   

原文地址:https://www.cnblogs.com/zzb-yp/p/11864368.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!