数据库: MySQL
相关插件:mybatis-spring-boot-starter,swagger2,代码自动生成器(见附件)
开发工具:IDEA
前提条件,相关JDK,maven,java环境都配置好了。
第一步使用idea搭建项目
选择相关依赖项。
一个基础的项目就建好了。
新建一个dome测试文件验证一下。
package com.example.shop;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class dome {
@RequestMapping("/hello")
public String hello() {
return "Hello Spring Boot!";
}
}
启动项目,打开浏览器,访问http://localhost:8080/hello
启动成功。
第二步,建立数据库。
使用数据库连接软件在mysql 数据库中建立自己的数据库。
CREATE TABLE `goods` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) COLLATE utf8_bin NOT NULL COMMENT '商品名称',
`type_id` int(11) DEFAULT NULL COMMENT '商品类型',
`price` decimal(7,2) DEFAULT NULL COMMENT '商品价格',
`imgages` varchar(60) COLLATE utf8_bin DEFAULT NULL COMMENT '商品图片',
`sell_count` int(11) DEFAULT NULL COMMENT '商品销售数量',
`creat_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间(自动生成)',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='商品表';
CREATE TABLE `goods_detail` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`goods_id` int(11) NOT NULL COMMENT '商品ID',
`detail` text COLLATE utf8_bin COMMENT '商品详情',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='商品详情表';
CREATE TABLE `goods_type` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`type_name` char(20) COLLATE utf8_bin NOT NULL COMMENT '分类名称',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='商品分类表';
第三步,使用代码生成工具自动生成相关代码。
下载代码生成器,修改generator.xml的相关配置,连接自己的数据库。
使用cmd命令打开生成器窗口,输入命令:
java -jar mybatis-generator-core-1.3.2.jar -configfile generator.xml -overwrite
将生成的文件,复制到项目中。
也可以不用代码生成器,自己建这些文件。这些文件都是很基础的,就不放源码了。使用代码生成器唯一的好处就是方便快捷。
第四步,安装插件,修改配置。
1、打开pom.xml文件,添加相关配置。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>shop</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>shop</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--集成mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
<!--动态生成接口文档-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
<finalName>shop</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<excludes>
<exclude>static/**/fonts/**</exclude>
<exclude>static/**/css/**</exclude>
</excludes>
</resource>
<resource>
<directory>src/main/resources</directory>
<filtering>false</filtering>
<includes>
<include>static/**/fonts/**</include>
<include>static/**/css/**</include>
</includes>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>
一定要注意自己项目框架版本
spring-boot-starter-parent的版本和相关插件的版本是不是适配的,不适配的话项目跑不起来。
可以去这个网站查看版本信息和版本依赖
2、application.properties 文件改成 application.yml ,并填写相关配置。
# DataSource Config
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://192.168.11.10:11306/test?useUnicode=yes&characterEncoding=UTF8
username: root
password: 123456
#jar方式下的tomcat配置
server:
port: 8011
#mybatis配置
mybatis:
mapper-locations: classpath*:com/example/shop/persistence/**/xml/*.xml
type-aliases-package: com.example.shop.persistence.entity
改名是为了配置简单。
3、修改启动类,ShopApplication。
package com.example.shop;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.example.shop.persistence.mapper")
public class ShopApplication {
public static void main(String[] args) {
SpringApplication.run(ShopApplication.class, args);
}
}
编写JSON工具。JSONResult。直接复制别人项目里面的拿来用就行。
package com.example.shop.utils;
/**
* @Description
* @Author by sm
* @Create 2017/05/09 11:42
*/
public class JSONResult {
public final static Integer SUCCESS=1;
public final static Integer ERROR=0;
private Integer code;
private String msg;
private Object result;
public JSONResult() {
}
public JSONResult(Integer code, String msg, Object result) {
this.code = code;
this.msg = msg;
this.result = result;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Object getResult() {
return result;
}
public void setResult(Object result) {
this.result = result;
}
/**
* 渲染失败数据
*
* @return result
*/
public static JSONResult renderError() {
JSONResult result = new JSONResult();
result.setCode(ERROR);
result.setMsg("error");
return result;
}
/**
* 渲染失败数据(带消息)
*
* @param msg 需要返回的消息
* @return result
*/
public static JSONResult renderError(String msg) {
JSONResult result = renderError();
result.setMsg(msg);
return result;
}
/**
* 渲染失败数据(带消息,带数据)
*
* @param msg 需要返回的消息
* @param obj 需要返回的对象
* @return result
*/
public static JSONResult renderError(String msg, Object obj) {
JSONResult result = renderError();
result.setMsg(msg);
result.setResult(obj);
return result;
}
public static JSONResult renderError(Integer code, String msg, Object obj) {
JSONResult result = renderError();
result.setCode(code);
result.setMsg(msg);
result.setResult(obj);
return result;
}
/**
* 渲染成功数据
*
* @return result
*/
public static JSONResult renderSuccess() {
JSONResult result = new JSONResult();
result.setMsg("success");
result.setCode(SUCCESS);
return result;
}
/**
* 渲染成功数据(带消息,带数据)
*
* @param obj 需要返回的对象
* @return result
*/
public static JSONResult renderSuccess(Object obj) {
JSONResult result = renderSuccess();
result.setResult(obj);
return result;
}
}
编写服务类和控制器。项目结构如下:
IGoodsService文件
package com.example.shop.modules.sys.service;
import com.example.shop.persistence.entity.Goods;
import com.example.shop.persistence.entity.GoodsDetail;
import com.example.shop.utils.JSONResult;
public interface IGoodsService {
// 查询
Goods getGoods(Integer id);
//新增 关联表新增
void insertGoodsAll(Goods goods, GoodsDetail goodsDetail);
}
GoodsServiceImp文件
package com.example.shop.modules.sys.service.impl;
import com.example.shop.persistence.entity.Goods;
import com.example.shop.persistence.entity.GoodsDetail;
import com.example.shop.persistence.mapper.GoodsDetailMapper;
import com.example.shop.persistence.mapper.GoodsMapper;
import com.example.shop.modules.sys.service.IGoodsService;
import com.example.shop.utils.JSONResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import static com.example.shop.utils.JSONResult.renderSuccess;
@Service
public class GoodsServiceImp implements IGoodsService {
@Autowired
private GoodsMapper goodsMapper;
@Autowired
private GoodsDetailMapper goodsDetailMapper;
/*
根据ID查询商品信息
*/
@Override
public Goods getGoods(Integer id){
return goodsMapper.selectByPrimaryKey(id);
}
/*
新增数据
关联表新增
*/
@Override
public void insertGoodsAll(Goods goods, GoodsDetail goodsDetail){
// 插入goods 表数据
goodsMapper.insertSelective(goods);
// 获取 新增的goods数据ID,赋值给 goodsDetail表的goodsId字段
goodsDetail.setGoodsId(goods.getId());
// 将数据插入 goodsDetail 表
goodsDetailMapper.insertSelective(goodsDetail);
}
}
备注下:这里用了关联表插入,需要修改persistence文件夹里面GoodsMapper.xml里面的相关代码
......
<insert id="insertSelective" parameterType="com.example.shop.persistence.entity.Goods" useGeneratedKeys="true" keyProperty="id">
.....
控制器文件 GoodsController
package com.example.shop.modules.sys.controller;
import com.example.shop.persistence.entity.Goods;
import com.example.shop.persistence.entity.GoodsDetail;
import com.example.shop.modules.sys.service.IGoodsService;
import com.example.shop.utils.JSONResult;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.swing.*;
@Api(tags = "商品接口")
@RestController
@RequestMapping("/sys/goods")
public class GoodsController {
@Autowired
private IGoodsService goodsService;
@ApiOperation(value = "查询",notes = "通过ID查商品详情")
@ApiImplicitParam(name = "id", value = "商品ID", required = true, dataType = "Int", paramType = "path")
@GetMapping("/{id}")
public JSONResult getGoods(@PathVariable("id") Integer id){
Goods goods = goodsService.getGoods(id);
return JSONResult.renderSuccess(goods);
}
/**
* 新增商品
* @param goods
* @return
*/
@ApiOperation(value = "新增",notes = "")
@PostMapping("/insert")
public JSONResult insertGoodsAll(Goods goods, GoodsDetail goodsDetail){
goodsService.insertGoodsAll(goods, goodsDetail);
return JSONResult.renderSuccess();
}
}
接口文档配置文件SwaggerConfig
package com.example.shop.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* @author wujiaxing
* <p>
* 接口文档 配置文件
* 使用Swagger2只需三步
* 1、导入Swaggerr依赖
* 2、配置Docket的bean
* 3、使用@Api等注解修饰
* </p>
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig {
/**
* 创建API应用
* appinfo()增加API相关信息
* 通过select()函数返回一个ApiSelectorBuilder实例,用来控制那些接口暴露给Swagger来展现
* 本例采用置顶扫描的包路径来定义指定要建立API的目录
*
* @return
*/
@Bean
public Docket createRestApi() {
Docket docket = new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.shop.modules.sys.controller"))
.paths(PathSelectors.any()).build();
return docket;
}
/**
* 创建改API的基本信息(这些基本信息会展示在文档页面中)
* 访问地址: http://项目实际地址/swagger-ui.html
* @return
*/
public ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("接口文档")
.description("java插件动态生成接口文档")
.termsOfServiceUrl("http://localhost")
.contact("an")
.version("2.9.2")
.build();
}
}
然后再启动项目,浏览器输入:http://localhost:8011/swagger-ui.html
测试接口
成功!
剩下的自己再慢慢写增删改查。