SpringBoot+MyBatis连接mysql数据库


环境
jdk:11
IDE:IDEA
mysql:8

新建项目

新建项目时勾选mybatis、jdbc、mysql

引入依赖

在springboot自动生成的pom.xml文件中引入所需要的依赖

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

导入mysql和springboot的关系依赖包,springboot会自动下载相关的jar包,非常方便

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
	<version>1.1.8</version>
</dependency>

用数据源的情况下会比单纯jdbc方便的多,也更加快速
我的项目用的数据源是druid,所以导入alibaba.druid

等待IDEA下载好相关的jar包后

编写application配置

SpringBoot+MyBatis连接mysql数据库
初建好的web程序,配置文件应该为application.properties,也可可修改为application.yml
笔者任务yml更方便编写

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/sakila?serverTimezone=GMT
    type: com.alibaba.druid.pool.DruidDataSource

其中usernamepassword为sql的用户名和密码
url也需根据本机情况进行配置,但在高版本的mysql中一定要在url后加入?serverTimezon=GMT
如果不调整时区,会导致连接不上mysql

编写实体层与mapper层

编写实体层
SpringBoot+MyBatis连接mysql数据库

package com.example.javatest.pojo.entity;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

@Getter
@Setter
@ToString
public class CustomerInfo{
    private Integer id;
    private String first_name;
    private String last_name;
    private String email;
    private String create_date;
    private Integer store_id;
}

创建实体类时,每个参数要与数据库字段名一一对应,切数据类型也要合适
创建customer实体对象(项目中用了lombok框架方便getter和setter)也可Alt+Insert批量创建私有变量的getter和setter
可在项目中创建mapper文件夹作为实体与数据库交流的层级,方便将来调用
SpringBoot+MyBatis连接mysql数据库
数据库实例:
SpringBoot+MyBatis连接mysql数据库
(mysql workbench)
根据数据库表结构构建mapper

package com.example.javatest.mapper;


import com.example.javatest.pojo.entity.CustomerInfo;
import org.apache.ibatis.annotations.*;

@Mapper
public interface  CustomerMapper {
    @Select("select * from customer where customer_id=#{id}")
    public CustomerInfo getCustomerInfoByID(Integer id);
}

根据id查找相应的customer

编写controller

package com.example.javatest.contoller;
import com.example.javatest.pojo.entity.CustomerInfo;
import com.example.javatest.mapper.CustomerMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
public class TestController {
    
    @Autowired
    CustomerMapper customerMapper;

    @GetMapping("/customerInfo")
    public CustomerInfo getCustomerInfo(Integer id){
        System.out.println(id);
        return customerMapper.getDeptByID(id);
    }
}

@Autowired可对mapper对象customer进行自动装配,不加入注解则会报错

测试

SpringBoot+MyBatis连接mysql数据库