Mybatis使用詳細(xì)說明
什么是MyBatis?
MyBatis 是一款優(yōu)秀的 Java 持久層框架,它通過 XML 或注解的方式將 Java 對象與數(shù)據(jù)庫中的記錄進(jìn)行映射。與傳統(tǒng)的 JDBC 相比,MyBatis 極大地簡化了數(shù)據(jù)庫操作代碼,讓開發(fā)者能夠更專注于業(yè)務(wù)邏輯而不是繁瑣的數(shù)據(jù)訪問細(xì)節(jié)。
MyBatis 的核心特點:
簡化了 JDBC 的復(fù)雜操作
支持動態(tài) SQL,能夠根據(jù)條件靈活構(gòu)建查詢語句
提供了強(qiáng)大的映射機(jī)制,支持復(fù)雜的對象關(guān)系映射
與 Spring 等主流框架無縫集成
學(xué)習(xí)曲線平緩,配置靈活
為什么選擇MyBatis?
與其它持久層框架的對比
相比于 Hibernate 這樣的全自動 ORM 框架,MyBatis 提供了更多的靈活性。MyBatis 允許你直接編寫原生 SQL,這在處理復(fù)雜查詢或需要優(yōu)化 SQL 性能時具有明顯優(yōu)勢。
主要優(yōu)勢:
靈活性:可以編寫原生 SQL,靈活控制查詢邏輯
性能優(yōu)化:直接控制 SQL 語句,便于性能調(diào)優(yōu)
簡化開發(fā):減少了大量 JDBC 模板代碼
易于學(xué)習(xí):學(xué)習(xí)曲線平緩,上手快速
與 Spring 集成良好:可以無縫集成到 Spring 框架中
環(huán)境搭建
創(chuàng)建springboot項目

導(dǎo)入mybatis起步依賴、mysql驅(qū)動及其他需求(首次使用下載時間會較長)

連接數(shù)據(jù)源


建立數(shù)據(jù)庫
范例代碼:
-- 創(chuàng)建數(shù)據(jù)庫
CREATE DATABASE IF NOT EXISTS demo;
USE demo;
-- 創(chuàng)建員工表
CREATE TABLE employees (
id INT PRIMARY KEY AUTO_INCREMENT,
employee_id VARCHAR(20) UNIQUE NOT NULL,
name VARCHAR(50) NOT NULL,
gender ENUM('男', '女') NOT NULL,
age INT,
department VARCHAR(50) NOT NULL,
position VARCHAR(50) NOT NULL,
salary DECIMAL(10,2),
hire_date DATE NOT NULL,
email VARCHAR(100),
phone VARCHAR(20),
address VARCHAR(200),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- 插入示例數(shù)據(jù)
INSERT INTO employees (employee_id, name, gender, age, department, position, salary, hire_date, email, phone, address)
VALUES
('EMP001', '張三', '男', 28, '技術(shù)部', '軟件工程師', 15000.00, '2020-03-15', 'zhangsan@company.com', '13800138001', '北京市海淀區(qū)'),
('EMP002', '李四', '女', 32, '人力資源部', 'HR經(jīng)理', 12000.00, '2018-06-20', 'lisi@company.com', '13800138002', '北京市朝陽區(qū)'),
('EMP003', '王五', '男', 35, '財務(wù)部', '財務(wù)主管', 18000.00, '2016-09-10', 'wangwu@company.com', '13800138003', '北京市西城區(qū)'),
('EMP004', '趙六', '女', 26, '市場部', '市場專員', 8000.00, '2021-01-08', 'zhaoliu@company.com', '13800138004', '北京市東城區(qū)'),
('EMP005', '錢七', '男', 30, '技術(shù)部', '高級工程師', 20000.00, '2019-11-25', 'qianqi@company.com', '13800138005', '北京市豐臺區(qū)'),
('EMP006', '孫八', '女', 29, '銷售部', '銷售經(jīng)理', 16000.00, '2020-07-30', 'sunba@company.com', '13800138006', '北京市石景山區(qū)'),
('EMP007', '周九', '男', 27, '技術(shù)部', '前端開發(fā)', 13000.00, '2021-03-12', 'zhoujiu@company.com', '13800138007', '北京市通州區(qū)'),
('EMP008', '吳十', '女', 33, '行政部', '行政主管', 11000.00, '2017-05-18', 'wushi@company.com', '13800138008', '北京市昌平區(qū)'),
('EMP009', '鄭十一', '男', 31, '財務(wù)部', '會計', 10000.00, '2019-08-22', 'zhengshiyi@company.com', '13800138009', '北京市大興區(qū)'),
('EMP010', '王芳', '女', 25, '市場部', '市場助理', 7000.00, '2022-02-14', 'wangfang@company.com', '13800138010', '北京市房山區(qū)');范例效果:

若已有數(shù)據(jù)庫,則直接連接

在application.properties文件中配置數(shù)據(jù)庫連接信息:

spring.application.name=demo #驅(qū)動類名稱 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver #數(shù)據(jù)庫連接的url spring.datasource.url=jdbc:mysql://localhost:3306/demo #連接數(shù)據(jù)庫的用戶名 spring.datasource.username=root #連接數(shù)據(jù)庫的密碼 spring.datasource.password=1234
實體類設(shè)計
在 MyBatis 中,實體類對應(yīng)數(shù)據(jù)庫中的表結(jié)構(gòu)。良好的實體類設(shè)計是使用 MyBatis 的基礎(chǔ)。
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Emp {
private Integer id; //ID
private String username; //用戶名
private String password; //密碼
private String name; //姓名
private Short gender; //性別 , 1 男, 2 女
private String image; //圖像url
private Short job; //職位 , 1 班主任 , 2 講師 , 3 學(xué)工主管 , 4 教研主管 , 5 咨詢師
private LocalDate entrydate; //入職日期
private Integer deptId; //部門ID
private LocalDateTime createTime; //創(chuàng)建時間
private LocalDateTime updateTime; //修改時間
}Mapper 接口設(shè)計
Mapper 接口定義了數(shù)據(jù)訪問的方法,可以使用注解完成接口的實現(xiàn)。(例如實例代碼中“分頁查詢”“查詢數(shù)據(jù)總數(shù)”“新增員工”“根據(jù)id查詢員工信息”這些功能的實現(xiàn))
@Mapper
public interface EmpMapper {
//分頁查詢
@Select("select * from emp limit #{start},#{pageSize}")
List<Emp> page(Integer start, Integer pageSize);
//條件分頁查詢
List<Emp> list(Integer start, Integer pageSize,String name, Short gender, LocalDate begin, LocalDate end);
//查詢數(shù)據(jù)總數(shù)
@Select("select count(*) from emp")
Long count();
//批量刪除員工
void delete(List<Integer> ids);
//新增員工
@Insert("insert into emp(username, name, gender, image, job, entrydate, dept_id, create_time, update_time) " +
"value(#{username},#{name},#{gender},#{image},#{job},#{entrydate},#{deptId},#{createTime},#{updateTime})")
void save(Emp emp);
//根據(jù)id更新員工信息
void update(Emp emp);
//根據(jù)id查詢員工信息
@Select("select * from emp where id = #{id}")
Emp getById(Integer id);
}Mapper XML 映射文件
XML 映射文件是 MyBatis 的核心,它定義了 SQL 語句和結(jié)果映射。在sql語句較復(fù)雜的情況下,不建議使用注解實現(xiàn)mapper接口(這樣會使得代碼顯得雜亂不易閱讀),而是在XML映射文件中編寫sql語句。需要注意的是,XML映射文件的路徑名稱必須于mapper接口路徑名稱相同。(EmpMapper接口文件路徑名稱為:cn.nuist.tlias.mapper.EmpMapper,XML映射文件路徑名稱也為:cn.nuist.tlias.mapper.EmpMapper)

mapper接口中的“分頁條件查詢”“批量刪除員工信息”和“根據(jù)id更新員工信息”功能在XML映射文件中實現(xiàn):
<?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="cn.nuist.tlias.mapper.EmpMapper">
<select id="list" resultType="cn.nuist.tlias.pojp.Emp">
select *
from emp
<where>
<if test="name != null and name != ''">
name like concat('%',#{name},'%')
</if>
<if test="gender != null">
and gender = #{gender}
</if>
<if test="begin != null and end != null">
and entrydate between #{begin} and #{end}
</if>
</where>
order by update_time desc
limit #{start},#{pageSize}
</select>
<delete id="delete">
delete
from emp
where id in
<foreach collection="ids" item="id" open="(" separator="," close=")">
#{id}
</foreach>
</delete>
<update id="update">
update emp
<set>
<if test="username != null and username != ''">
username = #{username}
</if>
<if test="name != null and name != ''">
name = #{name}
</if>
<if test="gender != null">
gender = #{gender}
</if>
<if test="image != null and image != ''">
image = #{image}
</if>
<if test="job != null">
job = #{job}
</if>
<if test="entrydate != null">
entrydate = #{entrydate}
</if>
<if test="deptId != null">
dept_id = #{deptId}
</if>
<if test="updateTime != null">
update_time = #{updateTime}
</if>
</set>
where id = #{id}
</update>
</mapper>動態(tài)SQL:靈活構(gòu)建查詢
MyBatis 的強(qiáng)大特性之一就是動態(tài) SQL,它允許你根據(jù)條件動態(tài)生成 SQL 語句。
<if> :根據(jù)條件包含 SQL 片段
<choose>, <when>, <otherwise>:實現(xiàn)類似 switch-case 的邏輯
<where>:智能處理 WHERE 條件,自動去除多余的 AND/OR
<set>:用于 UPDATE 語句,智能處理 SET 子句
<foreach>:遍歷集合,常用于 IN 條件或批量操作
<trim>:更靈活的字符串修剪功能
<bind>:創(chuàng)建變量并在當(dāng)前上下文使用
到此這篇關(guān)于Mybatis使用詳細(xì)說明的文章就介紹到這了,更多相關(guān)Mybatis使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Mybatis動態(tài)Sql標(biāo)簽使用小結(jié)
本文主要介紹了Mybatis動態(tài)Sql標(biāo)簽使用,常用的動態(tài)sql標(biāo)簽包括?if、choose(when、otherwise)、trim(where、set)、foreach,下面就來介紹一下2024-04-04
Java中l(wèi)ong類型與Long類型的區(qū)別和大小比較詳解
這篇文章主要給大家介紹了Java中l(wèi)ong類型與Long類型區(qū)別和大小比較的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2017-11-11
SpringBoot實現(xiàn)事件監(jiān)聽(異步執(zhí)行)的示例代碼
事件監(jiān)聽是一種機(jī)制,可以定義和觸發(fā)自定義的事件,以及在應(yīng)用程序中注冊監(jiān)聽器來響應(yīng)這些事件,本文主要介紹了SpringBoot實現(xiàn)事件監(jiān)聽(異步執(zhí)行)的示例代碼,感興趣的可以了解一下2024-08-08
SpringCloud+Redis實現(xiàn)Api接口限流防止惡意刷接口
接口限流是為了保護(hù)系統(tǒng)和服務(wù),防止因為過多的請求而崩潰,本文主要介紹了SpringCloud+Redis實現(xiàn)Api接口限流防止惡意刷接口,具有一定的參考價值,感興趣的可以了解一下2024-03-03
java發(fā)起http請求調(diào)用post與get接口的方法實例
在實際開發(fā)過程中,我們經(jīng)常需要調(diào)用對方提供的接口或測試自己寫的接口是否合適,下面這篇文章主要給大家介紹了關(guān)于java發(fā)起http請求調(diào)用post與get接口的相關(guān)資料,需要的朋友可以參考下2022-08-08

