搭建SpringBoot和Mysql Demo

本文介绍了如何在已有的SpringBoot项目基础上集成MySQL数据库,通过添加Mybatis依赖,配置数据库连接,创建表和对应的实体类,设计Mapper接口和服务层,最后实现RESTful接口对外提供服务。文章强调了代码组织和业务逻辑划分的重要性。
摘要由CSDN通过智能技术生成

1. 引言

在上一篇文章中,介绍了如何搭建一个SpringBoot项目;本篇文章,在上一篇文章的基础上,接着介绍下怎样实现SpringBootMySQL的整合。在后端开发中,数据库开发是绕不开的话题,开发中很多的时间都是在和数据库打交道。比如APP传递的数据需要进行持久化,方便下一次来获取;存储设备运行日志,将设备的执行日志存放到数据库中,方便排查错误,开放接口方便用户进行自主查询。因此,接下来就来搭建一个SpringBootMySQL项目,并且在结尾的地方会指出新手会触犯的一些规范。

2. Demo搭建

2.1 环境介绍
2.2 在pom.xml文件中填入依赖
<dependencies>
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.2.0</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.27</version>
    </dependency>
</dependencies>

pom.xml文件中,添加了两个依赖分别是MybatisMysqlMybatis用户表与类实体之间的转换,Mysql用于连接数据库。

2.3 在 src/main/resource目录下的application.properties 添加以下配置
spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase?useSSL=false&serverTimezone=UTC
spring.datasource.Devicename=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
2.4 创建表和实体类,该类和数据库表中列进行对应
CREATE DATABASE mydatabase;
USE mydatabase;

CREATE TABLE `device` (
	`id` BIGINT(20) NOT NULL AUTO_INCREMENT,
	`name` VARCHAR(20) NOT NULL COMMENT '设备name' COLLATE 'utf8mb4_general_ci',
	PRIMARY KEY (`id`) USING BTREE
);
public class Device {
    private Long id;
    private String name;

    // getters and setters
}
2.5 创建 Mybatis mapper接口,用于查询数据库设备信息
@Mapper
public interface DeviceMapper {
    @Select("SELECT * FROM device")
    List<Device> getAllDevices();
    
    @Insert("INSERT INTO device(name) VALUES(#{name})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    void save(Device device);
}
2.6 创建一个Service层,并使用mapper来连接数据库
@Service
public class DeviceService {
    
    private final DeviceMapper deviceMapper;

    public UserService(DeviceMapper deviceMapper) {
        this.deviceMapper = deviceMapper;
    }

    public List<Device> findAll() {
        return deviceMapper.findAll();
    }

    public void save(Device device) {
        deviceMapper.save(device);
    }
}
2.7 开放接口操作数据库
@RestController
@RequestMapping("/devices")
public class DeviceController {
    private final DeviceService deviceService;

    public DeviceController(DeviceService deviceService) {
        this.deviceService = deviceService;
    }

    @GetMapping
    public List<Device> getAllDevices() {
        return deviceService.findAll();
    }
    
    @PostMapping
    public void save(@RequestBody Device device) {
        deviceService.save(device);
    }
}
2.8 在终端中启动项目
mvn spring-boot:run

项目启动成功后,可以使用PostMan对接口进行测试;使用Get,请求地址 /devices,可以获取所有的devices;采用POST时,可以在数据库中添加一个Device

3. 结尾

如上步骤,就可以整合SpringBootMyBatisMySQL。流程主要包括:

在这里插入图片描述

在整个流程中,有些规范:

  • controller层:这里暴露出接口路径,暴露入参,因此这里应该要简洁明了,业务逻辑切记不要写在这里,这样显得代码又臭又长,毫无逻辑,难于维护。
  • service层:这里才是业务逻辑主要实现的地方,具体的业务也需要划分,模块化,切记不要重复写一样的代码。
  • mapper层:持久层负责与数据库进行交互,存储和检索数据。一般使用MyBatis等持久化框架来实现这一层。
下面是使用 IntelliJ IDEA 搭建 Spring Boot MyBatis 项目的步骤: 1. 打开 IntelliJ IDEA,选择 File -> New -> Project,然后选择 Spring Initializr。在弹出的窗口中,选择 Spring Boot 版本、Java 版本,然后填写 Group 和 Artifact 信息。在 Dependencies 中选择 “MyBatis” 和 “MySQL Driver”,然后点击 Next。 2. 在 Project Name 和 Project Location 中填写项目名称和项目存储位置,然后点击 Finish。 3. 在 pom.xml 文件中添加以下依赖项: ```xml <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>${mybatis-spring-boot-starter.version}</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql-connector-java.version}</version> </dependency> ``` 4. 在 application.properties 文件中添加数据库连接信息: ``` spring.datasource.url=jdbc:mysql://localhost:3306/test?useSSL=false&useUnicode=true&characterEncoding=UTF-8 spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.jdbc.Driver ``` 5. 创建 mybatis-config.xml 文件。在 src/main/resources 目录下创建一个名为 mybatis-config.xml 的文件,并添加以下内容: ```xml <?xml version="1.0" encoding="UTF-8" ?> <configuration> <settings> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings> </configuration> ``` 6. 创建 Mapper 接口和对应的 Mapper.xml 文件。在 src/main/java 目录下创建一个名为 com.example.demo.mapper 的包,并创建一个名为 UserMapper 的接口,代码如下: ```java package com.example.demo.mapper; import com.example.demo.entity.User; import org.apache.ibatis.annotations.Mapper; import java.util.List; @Mapper public interface UserMapper { List<User> findAll(); } ``` 在 src/main/resources 目录下创建一个名为 UserMapper.xml 的文件,并添加以下内容: ```xml <?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.example.demo.mapper.UserMapper"> <select id="findAll" resultType="com.example.demo.entity.User"> select * from user </select> </mapper> ``` 7. 在 Spring Boot 启动类中添加 @MapperScan 注解,扫描 Mapper 接口的路径。 ```java package com.example.demo; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @MapperScan("com.example.demo.mapper") public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } ``` 至此,一个简单的 Spring Boot MyBatis 项目就搭建完成了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值