@[TOC](SpringBoot: RESTful Web APP连接mysql(mybatis))
0. 系统版本
- 操作系统:window10
- spring boot :2.1.4 release
- eclipse Version : 2019-03 (4.11.0)
- java : Oracle JDK 1.8
- maven : 3.5.4
1. mysql中新建表user
执行以下sql
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT '' ,
`email` varchar(255) DEFAULT '' ,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
2. 配置application.properties
配置MySQL数据源和mybatis配置文件位置
修改src/main/resources/application.properties文件,内容如下:
spring.datasource.url=jdbc:mysql://localhost:3306/db_example?serverTimezone=GMT
spring.datasource.username=root
spring.datasource.password=yourpassword
mybatis.config-location=classpath:mybatis-config.xml
mybatis.mapper-locations=classpath:mybatis/*Mapper.xml
3. 修改POM.xml
- 首先需要继承母POM: spring-boot-starter-parent
- 选用依赖:
- spring-boot-starter-web
- spring-boot-starter-test
- mybatis-spring-boot-starter
- mysql-connector-java
- spring-boot-devtools
- 构建组件:spring-boot-maven-plugin (打包用)
<?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.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.hiramchen</groupId>
<artifactId>SpringBoot-rest-mybatis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>SpringBoot-rest-mybatis</name>
<description>SpringBoot-rest-service</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.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.1</version>
</dependency>
<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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
4. 创建模型User.java
package com.hiramchen.mybatis.model;
public class User {
private Integer id;
private String name;
private String email;
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
}
5. 创建Mapper类UserMapper.java
package com.hiramchen.mybatis.mapper;
import java.util.List;
import java.util.Optional;
import com.hiramchen.mybatis.model.User;
public interface UserMapper {
public List<User> findAll();
public Optional<User> findById(Integer id);
public void insert(User user);
public void update(User user);
public void deleteById(Integer id);
}
6. 创建控制器UserController.java
编写RESTful风格的接口
package com.hiramchen.mybatis.controller;
import java.util.List;
import java.util.Optional;
import javax.swing.text.html.Option;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.hiramchen.mybatis.mapper.UserMapper;
import com.hiramchen.mybatis.model.User;
@RestController
@RequestMapping("/api/user")
public class UserController {
@Autowired
private UserMapper userMapper;
@GetMapping
public List<User> getAllUsers(){
return userMapper.findAll();
}
@GetMapping(path="/{id}")
public User getUser(@PathVariable Integer id) {
Optional<User> opt = userMapper.findById(id);
if (opt.isPresent()) {
return opt.get();
}
else {
return new User();
}
}
@PostMapping
public String addNewUser(@RequestBody User user) {
User n = new User();
n.setName(user.getName());
n.setEmail(user.getEmail());
userMapper.insert(n);;
return "Saved";
}
@PostMapping("/{id}")
public String editUser(@PathVariable Integer id,@RequestBody User user) {
Optional<User> opt = userMapper.findById(id);
if (opt.isPresent()) {
User n = opt.get();
n.setName(user.getName());
n.setEmail(user.getEmail());
userMapper.update(n);
return "Modified";
}
else {
return "Can't find this item!";
}
}
@DeleteMapping("/{id}")
public String deleteUser(@PathVariable Integer id) throws Exception{
try {
userMapper.deleteById(id);
return String.format("Delete item %d success", id);
}
catch(Exception e) {
return "Delete Failed";
}
}
}
7. mybatis配置文件
在src/main/resources下新建一个mybatis-config.xml文件,按需求配置,不加该文件,直接使用默认值也是可以运行的。
<?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="useGeneratedKeys" value="true"/>
<setting name="useColumnLabel" value="true" />
<setting name="mapUnderscoreToCamelCase" value="true" />
</settings>
</configuration>
8. mybatis mapper文件
新建src/main/resources/mybatis/UserMapper.xml文件,写入对应的sql操作
<?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.hiramchen.mybatis.mapper.UserMapper">
<select id="findAll" resultType="com.hiramchen.mybatis.model.User">
select * from user order by id desc
</select>
<select id="findById" resultType="com.hiramchen.mybatis.model.User">
select * from user where id = #{id}
</select>
<insert id="insert" parameterType="com.hiramchen.mybatis.model.User" useGeneratedKeys="true" keyProperty="id" keyColumn="id">
insert into user(name,email)
values(#{name},#{email})
</insert>
<update id="update" parameterType="com.hiramchen.mybatis.model.User">
update user
<set>
<if test="name != null">name=#{name},</if>
<if test="email != null">email=#{email},</if>
</set>
where id=#{id}
</update>
<delete id="deleteById">
delete from user where id=#{id}
</delete>
</mapper>
9. 入口Application.java修改
增加一个@MapperScan()注解就好
package com.hiramchen.mybatis;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.hiramchen.mybatis.mapper")
public class SpringBootRestMybatisApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootRestMybatisApplication.class, args);
}
}
10. 测试
自己通过前端(表单、ajax、promise,fetch等)或者一些能发送请求的小工具来测试接口:
- 新增几个User
POST: http://localhost:8080/api/user
注意content-type=application/json - 查询所有User
GET: http://localhost:8080/api/user - 查询一个User
GET: http://localhost:8080/api/user/1 - 修改User
POST: http://localhost:8080/api/user/1 - 删除User
DELETE: http://localhost:8080/api/user/1