开始前的准备:
- 编辑器
IntelliJ IDEA
- 可以正常使用的
MySQL
进入正题
1. 使用IDEA构建一个SpringBoot
项目,注意创建时添加上mysql
和mybatis
的相关依赖,生成的SpringBoot
项目结构如下图所示:
关于如何创建SpringBoot项目请参见SpringBoot入门系列--快速构建SpringBoot应用
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 http://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.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.lingfeng</groupId>
<artifactId>spring-boot-mybatis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-boot-mybatis</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<mybatis-spring-boot-starter.version>2.0.1</mybatis-spring-boot-starter.version>
</properties>
<dependencies>
<!-- spring-boot-web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- mybatis-spring-boot -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>${mybatis-spring-boot-starter.version}</version>
</dependency>
<!-- mysql driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2. 在applicaiton.yml
(或者是application.properties
)中配置MySQL
数据库信息,此处还可以配置服务器启动时执行的脚本
spring:
datasource:
username: root
password: password
url: jdbc:mysql://localhost:3306/allen
driver-class-name: com.mysql.cj.jdbc.Driver
# 下面的配置是为了在项目启动时执行初始化sql脚本
continue-on-error: true
initialization-mode: always
platform: mysql
# 执行初始化脚本所在路径
schema: classpath:schema.sql
schema-username: root
schema-password: password
3. 编写Mapper
@Mapper
public interface UserMapper {
@Select("SELECT * FROM USER_TAB WHERE NAME = #{name}")
User findByName(@Param("name") String name);
@Insert("INSERT INTO USER_TAB(NAME, AGE) VALUES(#{name}, #{age})")
int insert(@Param("name") String name, @Param("age") Integer age);
@Update("UPDATE USER_TAB SET NAME = #{name} ,AGE = #{age} WHERE ID = #{id}")
int updateUserById(@Param("id") Long id, @Param("name") String name, @Param("age") Integer age);
@Delete("DELETE FROM USER_TAB WHERE ID = #{id}")
int deleteUserById(@Param("id") Long id);
}
4. 编写相关的 Dao ,Service 和 Controller,结构如下
5. 在Controller层定义的如下几个接口:
package com.lingfeng.contolller.impl;
import com.lingfeng.contolller.IUserController;
import com.lingfeng.entity.User;
import com.lingfeng.service.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
* @Author: lingfeng
* @Date: 2019/7/14 23:28
*/
@RestController
@RequestMapping(path = "/users")
public class UserControllerImpl implements IUserController {
private static final Logger LOGGER = LoggerFactory.getLogger(UserControllerImpl.class);
@Autowired
private IUserService userService;
@GetMapping
@Override
public User getUserByName(@RequestParam("name") String name) {
LOGGER.info("Search user by name: {}", name);
User user = userService.getUserByName(name);
LOGGER.info("Found user is {}", user.toString());
return user;
}
@PostMapping
@Override
public void createUser(@RequestBody User user) {
userService.insertUserInfo(new User(user.getName(), user.getAge()));
LOGGER.info("create user is {}", user.toString());
}
@PutMapping
@Override
public void updateUser(@RequestBody User user) {
userService.updateUser(user);
}
@DeleteMapping
@Override
public void deleteUser(@RequestParam("id") Long id) {
userService.deleteUser(id);
}
}
6. 对应的有4个rest接口,springboot启动后可直接访问
- 新增User:
curl -X POST -H 'Content-Type: application/json' -i http://localhost:8003/users --data '{
"name":"wangwu",
"age":14
}'
- 根据name查询User
curl -X GET -i 'http://localhost:8003/users?name=wangwu'
- 根据id更新User
curl -X PUT -H 'Content-Type: application/json' -i http://localhost:8003/users --data '{
"id":1,
"name":"wangwu",
"age":15
}'
- 根据id删除User
curl -X DELETE -i 'http://localhost:8003/users?id=1'
至此,一个简单的SpringBoot+Mybatis+MySQL的demo就完成了,后面针对异常处理,日志记录,单元测试等内容补充完成后放置GitHUB链接.