本篇会加入个人的所谓鱼式疯言
❤️❤️❤️鱼式疯言:❤️❤️❤️此疯言非彼疯言
而是理解过并总结出来通俗易懂的大白话,
小编会尽可能的在每个概念后插入鱼式疯言,帮助大家理解的.
🤭🤭🤭可能说的不是那么严谨.但小编初心是能让更多人能接受我们这个概念 !!!
前言
在当今这个数据驱动的时代,MyBatis以其卓越的性能和灵活性,成为了开发者们的首选ORM框架。它不仅简化了数据库操作的复杂性,还赋予了代码更高的可维护性和可读性。让我们一起探索MyBatis的魔力,如何让数据库交互变得既优雅又高效。
目录
-
Mybatis的初识
-
Mybatis的配置
-
Mybatis的使用讲解
一. Mybatis的初识
1. Mybatis 是什么?
Mybatis
是一个 开源的持久框架 , Mybatis 可以允许使用 简单的xml 和注解 来使用SQL语句
来操作数据库, 并可以把这些数据库返回的数据映射到Java对象
上。
2. Mybatis的优势
那么Mybatis 为啥行? 为啥能呢?
- SQL 映射: Mybatis 可以讲从数据库返回的字段映射到具体对象的相同属性上。
- 灵活性: 开发人员可以 灵活的使用Mybatis 来写原生的SQL 语句 ,或者通过一些配置来控制SQL的执行过程, 不需要通过
JDBC的方式来生硬的操作
数据库。
- 多样性: Mybatis可以 操作多种数据库 ,如:
MySQL
、PostgreSQL
、Oracle
等…
- 集成性: 在Java Spring中就 集成了Mybatis 的框架 。
二. 使用Mybatis的准备工作
1. pom的配置
核心依赖:
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
如上图,在 pom
文件中,加入依赖:
-
mybatis
的框架依赖 -
mysql
驱动的依赖
2. yml的配置
spring:
application:
name: mybatis-demo
# 数据库配置信息
datasource:
url: jdbc:mysql://127.0.0.1:3306/mybatis_test?characterEncoding=utf8&useSSL=false
username: root
password: 个人密码
driver-class-name: com.mysql.cj.jdbc.Driver
基本连接配置说明:
spring: datasource:url
: 表示连接数据库的URL(网址)
spring:datasource:username
:表示连接数据库的用户名
spring:datasource:password
: 连接数据库需要的输入的密码
spring:datasource:driver-class-name
:打开数据库必要的MySQL的驱动程序
鱼式疯言
这时就有小伙伴问了, 到底什么是配置文件, 我们为什么要在配置文件中写这些信息?
配置文件: 简单来说就一些定制化的功能设置, 如果要连接数据库, 我们就需要定制化的把
URL
,用户名
,密码
,驱动
等这些基本的功能放在配置文件中。
配置文件中描述这该功能的细枝末节, 如果要使用该功能的话, 就可以通过配置文件去定制化的使用~
除了上面必须要配置的MySQL 连接外, 还要下面这些根据 Mybatis功能
来配置的内容
Mybatis:configuration:log-impl
: 表示配置的日志信息(info,error等各种日志信息提示)
Mybatis:mapper-locations
:表示使用Mybatis 的XML文件操作的路径
(下一篇重点讲解)
Mybatis:configuration:map-underscore-to-camel-case
: 驼峰是否自动转化 (下面内容重点讲解)
3. 连接数据库,创建实体类
这里小编使用的 IDEA 的专业版
,专业版是需要激活码的,
小伙伴们自行去网上搜索 激活码和小编一样使用下面的 MySQL数据库的可视化界面 来观察/操作MySQL。
<1>. 连接本地数据库
如上图,这样就可以正常的连接我们的数据库。
<2>. 创建实体类
- 创建
UserInfoDo
类
- 将数据库的 字段 转化为Java的 类属性
package com.example.mybatis_test.Mapper.dataobject;
import lombok.Data;
import java.util.Date;
@Data
public class UserInfo {
private Integer id;
private String username;
private String password;
private Integer age;
private Integer gender;
private Integer deleteFlag;
private Date createTime;
private Date updateTime;
}
鱼式疯言
那么问题来了,
- 数据库字段的转化Java的属性是怎么转换的?
转化口诀: 每遇到字段的
_
的 下一个字母就大写 ! ! !例如: delete_flag --> deleteFlag (
如果是类名首字母需要小写字母转化大写字母
)
- 如此 Java的驼峰转化为数据库中字段的下划线
首字母: 大写字母直接改成
小写字母
(不是类名就不需要改
)非首字母: 大写字母前面加上
_
并将大写字母改成小写。
UserInfo -> user_info
4. 建立 UserMapper 接口类
package com.example.mybatis_test.Mapper;
import com.example.mybatis_test.Mapper.dataobject.UserInfo;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface UserMapper {
}
这里接口加上
@Mapper
注解的方式操作Mybatis
, 书写SQL 语句来实现对于MySQL的 增删改查 操作!
准备工作都差不多了, 下面开始吧~
三. 使用 Mybatis 操作MySQL
对应Mybatis 操作MySQL 的方式有两种:
-
使用注解书写
SQL语句
操作MySQL -
使用
XML
配置文件操作MySQL
而在本篇文章中,主要是通过注解的方式使用Mybatis 来操作数据库。
在下一篇文章中,小编会推出XML 方式来操作数据库~~
1. 查
<1>. 不带参数的查询
package com.example.mybatis_test.Mapper;
import com.example.mybatis_test.Mapper.dataobject.UserInfo;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface UserMapper {
@Select("select * from user_info")
List<UserInfo> selectAll();
}
操作流程:
-
使用
@Select
表明我们需要查询数据库~ -
然后使用 “” , 在"" 中书写我们需要查询的SQL 语句~
-
验证结果, 测试SQL 语句是否查询成功!
如上图, 我们通过测试,成功查询到对应的表中的内容~
鱼式疯言
怎么测试?
问的好 ! ! !
- 按住键盘上的:
alt + ins
就会出现下面测试两字
- 勾选需要测试的方法并点击确认
- 就会跳转到测试类中,记得每个测试类上面要加上
@SpringBootTest
和 每个测试方法都需要加上@Test
, 这样就可以对我们写的方法进行测试了~
package com.example.mybatis_test.Mapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest
class UserMapperTest {
@Autowired
UserMapper userMapper;
@Test
void selectAll() {
System.out.println(userMapper.selectAll());
}
}
<2>. 带参数的查询
package com.example.mybatis_test.Mapper;
import com.example.mybatis_test.Mapper.dataobject.UserInfo;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface UserMapper {
// 带参数的查询
// 按顺序和名字带参
@Select("select * from user_info where password = #{password} and age = #{age} ")
List<UserInfo> selectByUsernameandage1(Integer age, String password);
// 不按顺序带参, 使用param 代参数顺序
@Select("select * from user_info where age = #{param1} and password = #{param2}")
List<UserInfo> selectByUsernameandage2(Integer age, String password);
// 注解绑定查找
@Select("select * from user_info where age = #{age} and password = #{password}")
List<UserInfo> selectByUsernameandage3(@Param("age") Integer age, @Param("password") String password);
}
这是我们三种带参数的查询方式:
查询流程:
-
表明对应的参数名和参数类型
-
一定要注意 ==返回值, 返回值, 返回值!!! == 这里是不止返回一个UserInfo 一个对象,所以需要用
List<UserInfo>
来接收~ -
使用
#{参数名}
, 如果是使用 @Param(“参数名”), 就必须要和 注解内的参数名 保持一致~~
鱼式疯言
上面是三种带参数的查询方法,效果是一样的(只要不写错的情况下),
但是如果要小编来推荐的话, 小编推荐也最常用的就是最后一种
@Param
, 通过 注解的方式来写 , 可以更好的标明自己需要使用的哪个注解, 更不容易出错~~
<3>. 字段名和属性名不相同
啊啊啊???
明明查询成功了, 为什么我们对于的creatTime 这个属性为空
因为啊,
对应Mybatis 而言, 一般只能将数据库字段名和Java类属性名完全相同的才进行赋值, 而
createTime
在数据库的字段名为create_time
, 虽然是查询到了, 但是由于他俩的名字不相同,所以就不会进行赋值, 所以为空~
所以对于这上面的问题, 聪明的程序猿们早就想出解决方案了, 这里小编就介绍三种解决方法哦~~
// 统一数据库的字段名和Java 的属性名
// 注意空格
// 使用 as 重名统一成 Java 属性
@Select("select id, username, password, age, gender, phone, delete_flag as deleteFlag, create_time as createTime, update_time as updateTime" +
" from user_info ")
List<UserInfo> selectAll2();
// 使用配置文件
@Select("select id, username, password, age, gender, phone, delete_flag , create_time , update_time " +
" from user_info ")
List<UserInfo> selectAll3();
// 使用注解转化
@Select("select id, username, password, age, gender, phone, delete_flag , create_time , update_time " +
" from user_info ")
@Results( id = "BaseMap", value = {
@Result(column = "delete_flag" , property = "deleteFlag"),
@Result(column = "create_time" , property = "createTime"),
@Result(column = "update_time" , property = "updateTime"),
})
List<UserInfo> selectAll4();
方案一:将数据库中的 字段名 as 重命名成Java驼峰属性
方案二: 使用yml 来配置
mybatis:
configuration:
map-underscore-to-camel-case: true
来配置驼峰自动转化, 但是一定要按照小编上面口诀来转化,如果不规范就会转换失败!
方法三: 通过@Result 的方式来建立 一个字段对应一个属性名的映射关系 :
colunmn
表示数据库字段名,property
表示Java类属性名
@Results( id = "BaseMap", value = {
@Result(column = "delete_flag" , property = "deleteFlag"),
@Result(column = "create_time" , property = "createTime"),
@Result(column = "update_time" , property = "updateTime"),
})
2. 增
<1>. 常规增加
// 传对象插入
@Insert("insert into user_info( username, password, age, gender, phone) " +
" values(#{username},#{password},#{age},#{gender},#{phone})")
Integer insert(UserInfo userInfo);
如上图, 增加流程
- 使用
@insert
注解标明,并且参数名用 对象UserInfo 来传递
- 注意返回值,一般都是些
Integer
的(不要写void ), 返回的 增加了多少条数据
- 书写SQL语句时,注意没添加
@Param
()标明时, 必须直接使用#{属性名}
,即可得到对应的数据。
<2>.使用注解并带返回id的增加
@Options(useGeneratedKeys = true , keyProperty = "id", keyColumn = "id")
// 使用参数传递,使用绑定参数
@Insert("insert into user_info( username, password,
age, gender, phone) " +
"values (#{userInfo.username},#{userInfo.password},
#{userInfo.age},#{userInfo.gender},#{userInfo.phone})")
// 注意这里还需要参数绑定
Integer insert2(@Param("userInfo") UserInfo userInfo);
操作变动:
- 书写
SQL语句
时, 注意使用了@param
, 就需要 ==#{userInfo.username} ==这样**#{对象名.属性名} 的格式来赋值**。
@Options
这个注解可以映射主键, 当插入数据时, 将 MySQL 的id注解映射到对象属性中 ~
- 使用
@Options
时, 注意useGeneratedKeys
要置为true, 然后对应 主键字段keyColumn
和 主键属性keyColumn 进行映射即可~~
3. 改
/**
*
* @param id 用户id
* @param username 需要修改后的用户名
* @return
*/
@Update("update user_info set username = #{username} where id = #{id}")
Integer update(@Param("id") Integer id, @Param("username") String username);
如上图
修改流程:
- 使用
@update
注解,正确书写修改的SQL
语句
- 返回值一般写为
Integer
(不可写为 void
), 返回数据库修改的条数
4. 删
/**
* 删除数据
* @param id 寻找的条件
* @return 返回删除的条数
*/
// 删除数据
@Delete("delete from user_info where id = #{id}")
Integer delete(@Param("id") Integer id);
删除流程:
-
先使用
@Delete
来标识删除, 并正确 书写删除SQL语句 -
返回值一般写
Integer (不可写void)
,表示 数据库内删除的条数
总结
-
. mybatis 的初识: 认识了
mybatis
是一种 高效操作数据库的框架 ,并且 灵活兼容 。 -
. Mybatis的配置: 只要配置
pom的依赖
和yml 的相关数据库的配置
和创建实体类和Mapper的等… 一系列准备工作~ -
最后就是通过使用注解的方式,对MySQL数据库 进行增删改查操作~
如果觉得小编写的还不错的咱可支持 三连 下 (定有回访哦) , 不妥当的咱请评论区 指正
希望我的文章能给各位宝子们带来哪怕一点点的收获就是 小编创作 的最大 动力 💖 💖 💖