前言
Spring boot项目目前是Java Web开发领域最受市场欢迎的Spring框架之一,也是构建分布式项目、微服务项目重要基础之一,Spring Boot免去了配置繁杂的依赖和配置,使得开发人员把更多的精力放在项目本身上,就Spring框架而言,Spring Boot可谓是集大成者,担负着敏捷开发,前后台分离、模块低耦合的神圣使命;麻将哥也是一个忠实的SpringBoot fans,这篇教程零基础的带大家从新建项目开始,完成一个流程的CRUD。本教程采用Spring Boot+Mybatis+Mysql实现,麻将哥MySql的版本是5.7,建议大家的Mysql是5.7或者5.7+。需要完整源码的小伙伴可以关注麻将哥的微信公众号“码匠心”自行获取,谢谢大家!
准备工作
编辑器:InteIIiJ IDEA
MySql数据库表设计:
IDEA新建Spring Boot 项目这篇文章就不再累赘,需要的小伙伴可以查看麻将哥的上一篇的博客。
构建项目
- 使用IDEA新建项目后,目录结构如下:
2.在curddemo目录新建5个package,分别为bean,config,controller,mapper,service,bean主要用来放置实体类文件,config要来放置放置Swagger接口文档的配置类文件,controller用来放置程序控制器(API)类文件,service用来放置处理业务逻辑的类文件,mapper用来放置于数据库映射相关的类文件。建成项目目录如下:
2.在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.1.9.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.yisio</groupId>
<artifactId>curddemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>curddemo</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>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-undertow</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- swagger -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!-- swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<!-- druid数据库连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
</build>
</project>
3.在resources目录的application.properties文件里配置mysql连接信息:
#Created by 码匠心 on 2019/10/05.
#MySQL配置
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url=jdbc:mysql://localhost:3306/springbootdemo?serverTimezone=UTC&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=root
#MyBatis日志配置
mybatis.config-location=classpath:/mybatis-config.xml
#端口配置
server.port=8080
4.在resources目录下新建mybatis日志文件mybatis-config.xml
<!--Created by 码匠心 on 2019/10/05.-->
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="logImpl" value="STDOUT_LOGGING" />
</settings>
</configuration>
5.在bean目录下新建实体类User.java
package com.yisio.curddemo.bean;
/**
* Created by 码匠心 on 2019/10/05.
*/
public class User {
public Integer UserId;
public String UserName;
public boolean Sex;
public boolean Wedlock;
public String Place;
public void setUserId(Integer UserId){this.UserId=UserId;}
public void setUserName(String UserName){this.UserName=UserName;}
public void setSex(boolean Sex){this.Sex=Sex;}
public void setWedlock(boolean Wedlock){this.Wedlock=Wedlock;}
public void setPlace(String Place){this.Place=Place;}
}
6.在config目录下新建Swagger在线接口文档的配置文件SwaggerConfig.java
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
//文档标题
.title(" Spring Boot RESTful API")
// 版本号
.version("1.0")
// 标题描述
.description("swagger在线文档")
.build();
}
}
7.在mapper目录下新建UserMapper接口文件,新建增删改查的四个方法
package com.yisio.curddemo.mapper;
import com.yisio.curddemo.bean.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
/**
* Created by 码匠心 on 2019/10/05.
*/
import java.util.List;
@Mapper
public interface UserMapper {
List<User> getAllUser();
int AddUser(User users);
int updateUser(@Param("users") User users);
int deleteUserByUserId(@Param("ids") String[] ids);
}
8.在mapper目录下新建UserMapper.xml文件,使用mybtis操作数据库
<!--Created by 码匠心 on 2019/10/05.-->
<?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">
<mapper namespace="com.yisio.curddemo.mapper.UserMapper">
<resultMap id="BaseResultMap" type="com.yisio.curddemo.bean.User">
<result column="UserId" property="UserId"/>
<result column="UserName" property="UserName"/>
<result column="Sex" property="Sex"/>
<result column="Wedlock" property="Wedlock"/>
<result column="Place" property="Place"/>
</resultMap>
<select id="getAllUser" resultMap="BaseResultMap">
select * from sysuser;
</select>
<insert id="AddUser" parameterType="com.yisio.curddemo.bean.User">
insert into sysuser(UserName,Sex,Wedlock,Place)
values(#{UserName,jdbcType=VARCHAR},
#{Sex,jdbcType=BOOLEAN},
#{Wedlock,jdbcType=BOOLEAN},
#{Place,jdbcType=VARCHAR})
</insert>
<update id="updateUser">
update sysuser
<set>
UserName=#{users.UserName,jdbcType=VARCHAR},
Sex=#{users.Sex,jdbcType=BOOLEAN},
Wedlock=#{users.Wedlock,jdbcType=BOOLEAN},
Place=#{users.Place,jdbcType=VARCHAR}
</set>
where UserId=#{users.UserId,jdbcType=INTEGER}
</update>
<delete id="deleteUserByUserId">
DELETE from sysuser where UserId in
<foreach collection="ids" separator="," open="(" close=")" item="id">
#{id}
</foreach>
</delete>
</mapper>
9.在service目录下新建业务逻辑类UserService.java
package com.yisio.curddemo.service;
import com.yisio.curddemo.bean.User;
import com.yisio.curddemo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* Created by 码匠心 on 2019/10/05.
*/
@Service
@Transactional
public class UserService {
@Autowired
UserMapper userMapper;
public List<User> getAllUser(){
return userMapper.getAllUser();
}
private void UserDo(User users)
{
users.setUserId(users.UserId);
users.setUserName(users.UserName);
users.setPlace(users.Place);
users.setSex(users.Sex);
users.setWedlock(users.Wedlock);
}
public int AddUser(User users) {
UserDo(users);
return userMapper.AddUser(users);
}
public int updateUser(User users){
UserDo(users);
return userMapper.updateUser(users);
}
public boolean deleteUserByUserId(String ids){
String[] split = ids.split(",");
return userMapper.deleteUserByUserId(split) == split.length;
}
}
10.在controller目录下新建业务接口类UserController.java
package com.yisio.curddemo.controller;
import com.yisio.curddemo.bean.User;
import com.yisio.curddemo.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
/**
* Created by 码匠心 on 2019/10/05.
*/
@RestController
@RequestMapping("/User/UserData")
@Api(value = "UserController",description = "用户管理")
public class UserController {
@Autowired
UserService userService;
@ApiOperation(value = "用户查询")
@RequestMapping(value = "/UserData",method = RequestMethod.GET)
public Map<String,Object> getAllUser(){
Map<String,Object> map=new HashMap<>();
map.put("User",userService.getAllUser());
return map;
}
@ApiOperation(value = "新增用户")
@RequestMapping(value = "/UserData/AddUser",method = RequestMethod.POST)
public String AddUser(User users) {
if (userService.AddUser(users)==1)
return "新增成功!";
return "新增失败!";
}
@ApiOperation(value = "修改用户")
@RequestMapping(value = "/UserData/updateUser",method = RequestMethod.PUT)
public String updateUser(User users){
if (userService.updateUser(users)==1)
return "修改成功!";
return "修改失败!";
}
@ApiOperation(value = "删除用户")
@RequestMapping(value = "/UserData/deleteUser/{ids}",method = RequestMethod.DELETE)
public String deleteUserByUserId(@PathVariable String ids){
if(userService.deleteUserByUserId(ids))
return "删除成功!";
return "删除失败!";
}
}
10.最后的项目结构如下:
11.点击右上角项目启动按钮,运行项目,启动窗口看到如下信息则说明项目启动成功
12.在浏览器里输入URL:http://localhost:8080/swagger-ui.html#/,Swagger界面如下:
到这里我们的项目就启动成功了,执行Swagger接口文档里面的各个接口就能执行相应的增删改查操作!