SpringBoot: RESTful Web APP连接mysql(mybatis)

本文详细介绍了如何在SpringBoot项目中配置MySQL数据源、集成Mybatis,创建User模型、Mapper及Controller,实现RESTful风格的接口,包括增删查改操作。读者将学习到如何配置application.properties、修改POM.xml、编写UserMapper和UserController,并通过HTTP请求测试接口。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

@[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
  • 选用依赖:
    1. spring-boot-starter-web
    2. spring-boot-starter-test
    3. mybatis-spring-boot-starter
    4. mysql-connector-java
    5. 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等)或者一些能发送请求的小工具来测试接口:

  1. 新增几个User
    POST: http://localhost:8080/api/user
    注意content-type=application/json
  2. 查询所有User
    GET: http://localhost:8080/api/user
  3. 查询一个User
    GET: http://localhost:8080/api/user/1
  4. 修改User
    POST: http://localhost:8080/api/user/1
  5. 删除User
    DELETE: http://localhost:8080/api/user/1
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值