1.构建SpringBoot项目
基于maven构建(Maven的安装与配置)
Next
Next
创建好项目后,添加Maven依赖
<!--第一步,让项目扩展springboot核心依赖-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
<relativePath/>
</parent>
<dependencies>
<!--第二步:选择依赖的模块,web模块-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.39</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<!-- 引用通用mapper -->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>2.0.2</version>
</dependency>
</dependencies>
结构图
Application类是直接放在springboot包下,如图
2.业务实现
RestUserController.java
package com.daniel.springboot.controller;
import com.daniel.springboot.pojo.User;
import com.daniel.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* @Author Daniel
* @Description Restful风格的Controller
**/
@RestController //@Controller无法返回jsp页面
@RequestMapping("/rest/user")
public class RestUserController {
@Autowired
private UserService userService;
//@RequestMapping(method = RequestMethod.GET)
@GetMapping//上述mapping的简写
public ResponseEntity<List<User>> list() {
List<User> users = userService.list();
return ResponseEntity.status(HttpStatus.OK).body(users);
}
//@RequestMapping(value = "{id}", method = RequestMethod.GET)// /user/{id}
//查
@GetMapping("{id}")
//@PathVariable可以将URL中占位符参数{id}绑定到处理器类的方法形参中@PathVariable(“id“)
public ResponseEntity<User> queryById(@PathVariable("id") Long id) {
//若ID小于1则返回400
if (id == null || id < 1) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
}
User user = userService.queryById(id);
//若ID为空则返回404
if (user == null) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
}
return ResponseEntity.ok(user);
}
//增
@PostMapping
public ResponseEntity<Void> save(User user) {
//若User对象为空则返回400
if (user == null) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
}
Integer count = userService.save(user);
if (count == null || count == 0) {
//插入失败,返回400
return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
}//创建对象成功,返回201
return ResponseEntity.status(HttpStatus.CREATED).body(null);
}
//删
@DeleteMapping("{id}")
public ResponseEntity<Void> delete(@PathVariable("id") Long id) {
//若id为空或者小于1返回400
if (id == null || id < 1) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
}
Integer count = userService.deleteById(id);
if (count == null || count == 0) {
//插入失败,返回404
return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
}//删除成功,返回204
return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null);
}
//改
@PutMapping
public ResponseEntity<Void> update(User user) {
//若User对象为空则返回400
if (user == null) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
}
Integer count = userService.update(user);
if (count == null || count == 0) {
//插入失败,返回400
return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
}//创建对象成功,返回204
return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null);
}
}
UserMapper.java
package com.daniel.springboot.mapper;
import com.daniel.springboot.pojo.User;
import tk.mybatis.mapper.common.Mapper;
/**
* @Author Daniel
* @Description 通用mapper,不需要写任何东西
**/
public interface UserMapper extends Mapper<User> {
}
User.java
package com.daniel.springboot.pojo;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Date;
/**
* @Author Daniel
* @Description JavaBean
**/
@Table(name = "user")//声明此对象映射到数据库的数据表,通过它可以为实体指定表
public class User {
@Id//用于声明一个实体类的属性映射为数据库的主键列
@GeneratedValue(strategy = GenerationType.IDENTITY)//为一个实体生成一个唯一标识的主键
private Long id;
private String userName;
private String password;
private String name;
private Date birthday;
private Long gender;
private Date created;
private Date updated;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public Long getGender() {
return gender;
}
public void setGender(Long gender) {
this.gender = gender;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getUpdated() {
return updated;
}
public void setUpdated(Date updated) {
this.updated = updated;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", userName='" + userName + '\'' +
", password='" + password + '\'' +
", name='" + name + '\'' +
", birthday=" + birthday +
", gender=" + gender +
", created=" + created +
", updated=" + updated +
'}';
}
}
UserServiceImpl.java
package com.daniel.springboot.service.impl;
import com.daniel.springboot.mapper.UserMapper;
import com.daniel.springboot.pojo.User;
import com.daniel.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @Author Daniel
* @Description 业务类实现类
**/
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public List<User> list() {
return userMapper.selectAll();
}
@Override
public User queryById(Long id) {
return userMapper.selectByPrimaryKey(id);
}
@Override
public Integer save(User user) {
return userMapper.insertSelective(user);//有选择性的插入
}
@Override
public Integer deleteById(Long id) {
return userMapper.deleteByPrimaryKey(id);
}
@Override
public Integer update(User user) {
return userMapper.updateByPrimaryKeySelective(user);
}
}
UserService.java
package com.daniel.springboot.service;
import com.daniel.springboot.pojo.User;
import java.util.List;
/**
* @Author Daniel
* @Description 业务层
**/
public interface UserService {
List<User> list();
User queryById(Long id);
Integer save(User user);
Integer deleteById(Long id);
Integer update(User user);
}
Application.java
package com.daniel.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import tk.mybatis.spring.annotation.MapperScan;
/**
* @Author Daniel
* @Description 第三步,通过注解来修饰当前的Application class
**/
@SpringBootApplication
@MapperScan("com.daniel.springboot.mapper")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
application.yml
server:
port: 8090 #指定端口
servlet:
context-path: /sb #指定访问路径
#数据源
spring:
datasource:
url: jdbc:mysql://localhost:3306/crm
driver-class-name: com.mysql.jdbc.Driver
username: root
password: root
#spring和mybatis的配置
mybatis:
type-aliases-package: com.daniel.springboot.pojo
#开启驼峰命名
configuration:
map-underscore-to-camel-case: true
#日志设置
logging:
level:
com.daniel: debug
# mapper-locations: com/daniel/springboot/mapper/**.xml
user.sql
/*
Navicat Premium Data Transfer
Source Server : win
Source Server Type : MySQL
Source Server Version : 50721
Source Host : localhost:3306
Source Schema : crm
Target Server Type : MySQL
Target Server Version : 50721
File Encoding : 65001
Date: 01/09/2020 09:58:53
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NULL DEFAULT NULL,
`user_name` varchar(60) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`password` varchar(60) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`name` varchar(60) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`birthday` date NULL DEFAULT NULL,
`gender` int(11) NULL DEFAULT NULL,
`created` datetime(0) NULL DEFAULT NULL,
`updated` datetime(0) NULL DEFAULT NULL
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, 'zhangsan', '123456', '张三', '2019-06-10', 1, '2019-06-10 10:03:52', '2019-06-10 10:03:55');
INSERT INTO `user` VALUES (2, 'lisi', '123456', '李四', '2019-06-03', 0, '2019-06-09 10:04:17', '2019-06-12 10:04:21');
SET FOREIGN_KEY_CHECKS = 1;
3.启动与测试
随便放一张图在static文件夹下,启动Application.java,访问
http://localhost:8090/sb/1.jpg
没有问题之后使用Insomnia工具进行测试
在左侧导航栏右键新建一个文件夹
3.1GET
在文件夹里新建Request
点击Create
发送URL:http://localhost:8090/sb/rest/user
3.2POST
发送URL:http://localhost:8090/sb/rest/user
插入部分信息
可以看到数据库已经更新
3.3PUT
发送URL:http://localhost:8090/sb/rest/user
修改部分信息
可以看到数据库已经更新
3.4DEL
发送URL:http://localhost:8090/sb/rest/user/3
删除id为3的字段
可以看到数据库已经更新