SpringBoot+Mybatis连接MySQL数据库方法及注意事项

本文详细介绍了如何使用SpringBoot与Mybatis连接MySQL数据库,从添加POM依赖到配置数据库连接,再到创建实体类、Mapper接口与XML文件,最后通过控制器进行测试。在实践过程中,特别提醒注意@MapperScan、mybatis.mapper-locations配置以及MySQL的时区和SQL模式设置,以避免常见错误。
摘要由CSDN通过智能技术生成

1、POM依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

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

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-beans</artifactId>
</dependency>

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.4.0</version>
</dependency>

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.2</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.1.5.RELEASE</version>
</dependency>

2、测试用数据库表结构

mysql数据库为test,数据库表为teacher,创建表语句如下:

create table teacher(
 tec_id varchar(16) not null primary key,
 tec_name varchar(16) not null,
 tec_age tinyint unsigned,
 tec_desc varchar(128)
);

往数据库插入一条数据

 

3、springboot maven 项目目录结构

4、配置到application.properties,添加MySQL数据库连接

#数据库连接:注意要加上时区
spring.datasource.url=jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

#配置mapper.xml文件存放路径
mybatis.mapper-locations=classpath:mapper/*.xml

5、在创建的mybatis目录(目录名可任意命名)下,新建MyBatis 数据库 Configuration 文件

package com.rctech.testmybatis.mybatis;

//import com.github.pagehelper.PageHelper;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springfra
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值