Springboot2.x 使用 MyBatis 链接 Mysql 数据库并开启SQL日志
参考
- Windows 外网无法访问mysql之防火墙设置
- Error querying database. Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Could no
- 解决org.apache.ibatis.binding.BindingException: Invalid bound statement (not found)问题
- mybatis官方文档
- 开启sql日志
引言
早在今年年初的时候实践过一次 springboot 使用 MyBatis 连接 mysql 数据库(2021.01.25),时间过了半年没有使用,忘记了,又复习了一遍。
环境
操作系统:macos
sprongboot版本:2.3.7.RELEASE
mysql版本:8.0.18
mybatis版本:2.1.4
编辑器:idea
正文
- pom.xml 引入依赖
<dependencies>
//pom.xml追加
<dependencies>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
// 8.0.33 以后引入的是 mysql-connector-j (2023/12/15)
<artifactId>mysql-connector-java</artifactId>
// mysql 8.+版本需要指定版本号
<version>8.0.18</version>
</dependency>
</dependencies>
- pom.xml 配置打包时不忽略 xml映射文件(防止xml文件不打包报错)
<build>
<!-- 防止xml映射文件被忽略-->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
- 配置文件 application.properties 中配置数据库连接信息与MyBatis配置
# 数据库连接地址
spring.datasource.url=jdbc:mysql://你的IP地址:3306/suddenly_online_learning_platform?characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC
# 数据库用户名&密码:
spring.datasource.username=你的账号
spring.datasource.password=你的密码
# 注意mysql5是com.mysql.jdbc.Driver (2023/12/15)
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#下面这些内容是为了让MyBatis映射
#指定Mybatis的Mapper文件 (对应位置是 resources/mappers )
mybatis.mapper-locations=classpath:mappers/*xml
#指定Mybatis的实体目录
mybatis.type-aliases-package=com.xxxxxx.suddenlynlinelearningplatform.mybatis.entity
# 开启日志 https://blog.csdn.net/u014641168/article/details/120947282 (2023/12/16)
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
- 创建实体 ,对应位置 entity/Student.java
@Data
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
public class Student implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
/**
* 账号
*/
private String account;
/**
* 密码
*/
private String password;
/**
* 用户名
*/
private String name;
/**
* 头像
*/
private String avatarUrl;
/**
* 性别
*/
private Byte gender;
/**
* 手机号
*/
private String phoneNumber;
/**
* 手机号验证状态
*/
private byte phoneVerificationStatus;
/**
* 账号
*/
private String bewrite;
/**
* 创建时间
*/
private Date createdAt;
/**
* 更新时间
*/
private Date updatedAt;
}
- 创建学生 Maper 接口,对应位置 maper/StudentMaper.java
@Mapper
public interface StudentMaper {
Student findById(Integer id);
}
- 创建 xml 映射文件,对应位置 resources/mappers/StudentMaper.xml,注意这里的xml文件名要与我们的 maper/*.java 文件名相同
<?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">
<!--这里对应Maper接口类的命名空间-->
<mapper namespace="com.xxxx.suddenlynlinelearningplatform.mapper.StudentMaper">
<!-- 这里 resultType 对应响应实体类,也可以是其他类型,请参考文档-->
<select id="findById" parameterType="int" resultType="com.xxxxxx.suddenlynlinelearningplatform.entity.Student">
select * from `students` where id = #{id}
</select>
</mapper>
- 创建学生 service,对应位置 service/StudentService.java
@Service
public class StudentService {
@Autowired
StudentMaper studentMaper;
public Student findById(Integer id){
return studentMaper.findById(id);
}
}
- 入口文件增加maper扫描注解
如果Mapper接口类已经设置了@Mapper注解,则会自动发现,无需此步骤
@SpringBootApplication
/**
* 开启缓存,需要显示的指定
*/
@EnableCaching
/**
* Maper映射扫描
*/
@MapperScan("com.xxx.xxxx.mapper")
public class SuddenlyNlineLearningPlatformApplication {
public static void main(String[] args) {
SpringApplication.run(SuddenlyNlineLearningPlatformApplication.class, args);
}
}
- 测试
@Api(tags = "测试类", value = "测试类")
@RestController
@RequestMapping("v1/test")
public class Test {
@Autowired
StudentService studentService;
@RequestMapping(value = "index", method = RequestMethod.GET)
public Student index(){
return studentService.findById(1);
}
}
总结
- 如果mysql位于虚拟机,请记得检测端口是否打开,参考:Windows 外网无法访问mysql之防火墙设置
2.xml与接口类的名字要一直,xml内的命名空间引入也要一致。
博 主 :夏秋初
地 址 :https://www.cnblogs.com/xiaqiuchu/p/15098258.html
如果对你有帮助,可以点一下 推荐 或者 关注 吗?会让我的分享变得更有动力~
转载时请带上原文链接,谢谢。
地 址 :https://www.cnblogs.com/xiaqiuchu/p/15098258.html
如果对你有帮助,可以点一下 推荐 或者 关注 吗?会让我的分享变得更有动力~
转载时请带上原文链接,谢谢。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义