MyBatis基礎操作完整指南

文章目錄

  • MyBatis簡介
  • 環境搭建
    • Maven依賴
    • 數據庫表結構
  • 核心配置
    • MyBatis配置文件
    • 數據庫配置文件
    • 實體類
  • 基礎CRUD操作
    • Mapper接口
    • Mapper XML映射文件
    • 工具類
    • 測試類
  • 動態SQL
    • 常用標簽
  • 高級特性
    • 一對一關聯映射
    • 一對多關聯映射
    • 分頁查詢
    • 使用注解方式

MyBatis簡介

MyBatis是Apache的一個開源項目,前身是iBatis。它是一個基于Java的持久層框架,主要特點包括:相比Hibernate等ORM框架,MyBatis更加輕量級,并且支持自定義SQL,能夠充分利用數據庫特性。

環境搭建

Maven依賴

首先在pom.xml中添加MyBatis相關依賴:

<dependencies><!-- MyBatis核心依賴 --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.13</version></dependency><!-- MySQL驅動 --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.33</version></dependency>
</dependencies>

數據庫表結構

創建一個用戶表:

CREATE TABLE `user` (`id` int(11) NOT NULL AUTO_INCREMENT,`username` varchar(50) NOT NULL,`email` varchar(100) DEFAULT NULL,`age` int(3) DEFAULT NULL,`created_time` datetime DEFAULT CURRENT_TIMESTAMP,PRIMARY KEY (`id`)
);

核心配置

MyBatis配置文件

創建mybatis-config.xml核心配置文件:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><!-- 屬性配置 --><properties resource="database.properties"/><!-- 設置 --><settings><!-- 開啟駝峰命名自動映射 --><setting name="mapUnderscoreToCamelCase" value="true"/></settings><!-- 類型別名 --><typeAliases><package name="com.example.entity"/></typeAliases><!-- 環境配置 --><environments default="development"><environment id="development"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="${database.driver}"/><property name="url" value="${database.url}"/><property name="username" value="${database.username}"/><property name="password" value="${database.password}"/></dataSource></environment></environments><!-- 映射器配置 --><mappers><mapper resource="mapper/UserMapper.xml"/></mappers>
</configuration>

數據庫配置文件

創建database.properties文件:

database.driver=com.mysql.cj.jdbc.Driver
database.url=jdbc:mysql://localhost:3306/mybatis
database.username=root
database.password=123456

實體類

創建User實體類:

package com.example.entity;import java.time.LocalDateTime;public class User {private Integer id;private String username;private String email;private Integer age;private LocalDateTime createdTime;// 構造方法public User() {}public User(String username, String email, Integer age) {this.username = username;this.email = email;this.age = age;}// getter和setter方法public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public LocalDateTime getCreatedTime() {return createdTime;}public void setCreatedTime(LocalDateTime createdTime) {this.createdTime = createdTime;}@Overridepublic String toString() {return "User{" +"id=" + id +", username='" + username + '\'' +", email='" + email + '\'' +", age=" + age +", createdTime=" + createdTime +'}';}
}

基礎CRUD操作

Mapper接口

創建UserMapper接口:

package com.example.mapper;import com.example.entity.User;
import java.util.List;public interface UserMapper {// 插入用戶int insertUser(User user);// 根據ID刪除用戶int deleteUserById(Integer id);// 更新用戶信息int updateUser(User user);// 根據ID查詢用戶User selectUserById(Integer id);// 查詢所有用戶List<User> selectAllUsers();// 根據用戶名查詢用戶List<User> selectUsersByUsername(String username);
}

Mapper XML映射文件

創建UserMapper.xml映射文件:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.example.mapper.UserMapper"><!-- 結果映射 --><resultMap id="userResultMap" type="User"><id property="id" column="id"/><result property="username" column="username"/><result property="email" column="email"/><result property="age" column="age"/><result property="createdTime" column="created_time"/></resultMap><!-- 插入用戶 --><insert id="insertUser" parameterType="User" useGeneratedKeys="true" keyProperty="id">INSERT INTO user (username, email, age)VALUES (#{username}, #{email}, #{age})</insert><!-- 根據ID刪除用戶 --><delete id="deleteUserById" parameterType="int">DELETE FROM user WHERE id = #{id}</delete><!-- 更新用戶信息 --><update id="updateUser" parameterType="User">UPDATE user SETusername = #{username},email = #{email},age = #{age}WHERE id = #{id}</update><!-- 根據ID查詢用戶 --><select id="selectUserById" parameterType="int" resultMap="userResultMap">SELECT id, username, email, age, created_timeFROM userWHERE id = #{id}</select><!-- 查詢所有用戶 --><select id="selectAllUsers" resultMap="userResultMap">SELECT id, username, email, age, created_timeFROM userORDER BY created_time DESC</select><!-- 根據用戶名查詢用戶 --><select id="selectUsersByUsername" parameterType="string" resultMap="userResultMap">SELECT id, username, email, age, created_timeFROM userWHERE username LIKE CONCAT('%', #{username}, '%')</select></mapper>

工具類

創建MyBatis工具類:

package com.example.util;import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;import java.io.IOException;
import java.io.InputStream;public class MyBatisUtil {private static SqlSessionFactory sqlSessionFactory;static {try {// 讀取配置文件InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");// 創建SqlSessionFactorysqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);} catch (IOException e) {e.printStackTrace();}}// 獲取SqlSessionpublic static SqlSession getSqlSession() {return sqlSessionFactory.openSession();}// 獲取自動提交的SqlSessionpublic static SqlSession getSqlSession(boolean autoCommit) {return sqlSessionFactory.openSession(autoCommit);}
}

測試類

創建測試類驗證CRUD操作:

package com.example.test;import com.example.entity.User;
import com.example.mapper.UserMapper;
import com.example.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;import java.util.List;public class MyBatisTest {public static void main(String[] args) {// 測試插入testInsert();// 測試查詢testSelect();// 測試更新testUpdate();// 測試刪除testDelete();}// 測試插入public static void testInsert() {SqlSession sqlSession = MyBatisUtil.getSqlSession();try {UserMapper mapper = sqlSession.getMapper(UserMapper.class);User user = new User("張三", "zhangsan@example.com", 25);int result = mapper.insertUser(user);sqlSession.commit();System.out.println("插入結果: " + result + ", 用戶ID: " + user.getId());} finally {sqlSession.close();}}// 測試查詢public static void testSelect() {SqlSession sqlSession = MyBatisUtil.getSqlSession();try {UserMapper mapper = sqlSession.getMapper(UserMapper.class);// 查詢所有用戶List<User> users = mapper.selectAllUsers();System.out.println("所有用戶: " + users);// 根據ID查詢if (!users.isEmpty()) {User user = mapper.selectUserById(users.get(0).getId());System.out.println("根據ID查詢: " + user);}} finally {sqlSession.close();}}// 測試更新public static void testUpdate() {SqlSession sqlSession = MyBatisUtil.getSqlSession();try {UserMapper mapper = sqlSession.getMapper(UserMapper.class);List<User> users = mapper.selectAllUsers();if (!users.isEmpty()) {User user = users.get(0);user.setAge(30);user.setEmail("updated@example.com");int result = mapper.updateUser(user);sqlSession.commit();System.out.println("更新結果: " + result);}} finally {sqlSession.close();}}// 測試刪除public static void testDelete() {SqlSession sqlSession = MyBatisUtil.getSqlSession();try {UserMapper mapper = sqlSession.getMapper(UserMapper.class);List<User> users = mapper.selectAllUsers();if (!users.isEmpty()) {int result = mapper.deleteUserById(users.get(0).getId());sqlSession.commit();System.out.println("刪除結果: " + result);}} finally {sqlSession.close();}}
}

動態SQL

MyBatis提供了強大的動態SQL功能,可以根據條件動態生成SQL語句:

常用標簽

<!-- if標簽:條件判斷 -->
<select id="selectUsersByCondition" parameterType="User" resultMap="userResultMap">SELECT * FROM userWHERE 1=1<if test="username != null and username != ''">AND username LIKE CONCAT('%', #{username}, '%')</if><if test="email != null and email != ''">AND email = #{email}</if><if test="age != null">AND age = #{age}</if>
</select><!-- where標簽:智能處理WHERE關鍵字和AND/OR -->
<select id="selectUsersWithWhere" parameterType="User" resultMap="userResultMap">SELECT * FROM user<where><if test="username != null and username != ''">username LIKE CONCAT('%', #{username}, '%')</if><if test="email != null and email != ''">AND email = #{email}</if><if test="age != null">AND age = #{age}</if></where>
</select><!-- choose、when、otherwise:類似switch語句 -->
<select id="selectUsersByChoose" parameterType="User" resultMap="userResultMap">SELECT * FROM user<where><choose><when test="username != null and username != ''">username LIKE CONCAT('%', #{username}, '%')</when><when test="email != null and email != ''">email = #{email}</when><otherwise>age &gt; 18</otherwise></choose></where>
</select><!-- set標簽:用于UPDATE語句 -->
<update id="updateUserSelective" parameterType="User">UPDATE user<set><if test="username != null and username != ''">username = #{username},</if><if test="email != null and email != ''">email = #{email},</if><if test="age != null">age = #{age}</if></set>WHERE id = #{id}
</update><!-- foreach標簽:循環處理集合 -->
<select id="selectUsersByIds" parameterType="list" resultMap="userResultMap">SELECT * FROM userWHERE id IN<foreach collection="list" item="id" open="(" separator="," close=")">#{id}</foreach>
</select>

高級特性

一對一關聯映射

<!-- 用戶訂單一對一關系 -->
<resultMap id="userWithOrderResultMap" type="User"><id property="id" column="user_id"/><result property="username" column="username"/><association property="order" javaType="Order"><id property="id" column="order_id"/><result property="orderNo" column="order_no"/><result property="amount" column="amount"/></association>
</resultMap><select id="selectUserWithOrder" resultMap="userWithOrderResultMap">SELECT u.id as user_id, u.username, o.id as order_id, o.order_no, o.amountFROM user uLEFT JOIN order o ON u.id = o.user_idWHERE u.id = #{id}
</select>

一對多關聯映射

<!-- 用戶訂單一對多關系 -->
<resultMap id="userWithOrdersResultMap" type="User"><id property="id" column="user_id"/><result property="username" column="username"/><collection property="orders" ofType="Order"><id property="id" column="order_id"/><result property="orderNo" column="order_no"/><result property="amount" column="amount"/></collection>
</resultMap><select id="selectUserWithOrders" resultMap="userWithOrdersResultMap">SELECT u.id as user_id, u.username,o.id as order_id, o.order_no, o.amountFROM user uLEFT JOIN order o ON u.id = o.user_idWHERE u.id = #{id}
</select>

分頁查詢

<!-- 分頁查詢 -->
<select id="selectUsersWithPage" parameterType="map" resultMap="userResultMap">SELECT * FROM userORDER BY created_time DESCLIMIT #{offset}, #{pageSize}
</select><!-- 查詢總數 -->
<select id="countUsers" resultType="int">SELECT COUNT(*) FROM user
</select>

使用注解方式

public interface UserMapper {@Insert("INSERT INTO user (username, email, age) VALUES (#{username}, #{email}, #{age})")@Options(useGeneratedKeys = true, keyProperty = "id")int insertUserWithAnnotation(User user);@Delete("DELETE FROM user WHERE id = #{id}")int deleteUserByIdWithAnnotation(@Param("id") Integer id);@Update("UPDATE user SET username = #{username}, email = #{email}, age = #{age} WHERE id = #{id}")int updateUserWithAnnotation(User user);@Select("SELECT * FROM user WHERE id = #{id}")@Results({@Result(property = "id", column = "id"),@Result(property = "username", column = "username"),@Result(property = "email", column = "email"),@Result(property = "age", column = "age"),@Result(property = "createdTime", column = "created_time")})User selectUserByIdWithAnnotation(@Param("id") Integer id);
}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/diannao/94531.shtml
繁體地址,請注明出處:http://hk.pswp.cn/diannao/94531.shtml
英文地址,請注明出處:http://en.pswp.cn/diannao/94531.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

go與grpc

目錄下載與安裝遇到的問題cmd中protoc找不到命令cmd中--go_out: protoc-gen-go: Plugin failed with status code 1.下載與安裝 下載protoc&#xff1a; https://github.com/protocolbuffers/protobuf/releases 點擊下載相應電腦版本即可&#xff0c;我是windows系統下載了pro…

2025年AI面試重構招聘新生態

當企業面臨業務擴張與人才競爭的雙重壓力&#xff0c;傳統招聘模式已難以滿足高效、精準、公平的人才篩選需求。尤其在校招季、藍領用工潮等關鍵節點&#xff0c;面試官超負荷運轉、跨地域協調困難、評估標準模糊等問題頻發。AI技術的深度介入正推動招聘行業從“經驗驅動”向“…

Rust進階-part5-trait

Rust進階[part5]_trait trait概述 在 Rust 中,trait 是一種定義共享行為的方式。它類似于其他語言中的接口,允許我們定義一組方法簽名,然后讓不同的類型去實現這些方法。通過 trait,我們可以實現多態性,即不同類型可以以統一的方式處理。 普通實現 使用 trait 關鍵字來…

【人工智能-18】機器學習:決策樹、隨機森林

上一期【人工智能-17】機器學習&#xff1a;KNN算法、模型選擇和調優、樸素貝葉斯分類 文章目錄一、決策樹1.使用理由2.技術二、隨機森林1.使用理由2.原理核心&#xff1a;Bagging 隨機特征子集3.優點和缺點一、決策樹 決策樹是一種監督學習算法&#xff0c;主要用于分類&…

RFID高頻讀寫器在工業生產線的使用優勢

在工業4.0浪潮下&#xff0c;智能制造對生產效率與精準度的要求日益提升。RFID技術憑借其獨特的技術優勢&#xff0c;成為工業場景中實現數據實時采集與流程優化的關鍵工具。本文主要從RFID高頻讀寫器出發&#xff0c;系統解析其在工業生產線中的使用優勢。RFID高頻讀寫器一、技…

大模型學習筆記

prompt 提示詞的構成&#xff1a; 指示&#xff1a;描述讓它做什么上下文&#xff1a;給出與任務相關的背景信息輸入&#xff1a; 任務的輸入信息輸出&#xff1a;輸出的格式 生成與檢索 生成&#xff1a; 優點&#xff1a;內容的多樣性、創造性缺點&#xff1a;存在不可控制 檢…

龍虎榜——20250806

上證指數繼續收陽線&#xff0c;創新高的概率較大&#xff0c;個股上漲多于下跌&#xff0c;但板塊輪動較明顯&#xff0c;高位板塊注意風險。深證指數較昨天放量收陽線&#xff0c;站上5日和10日均線繼續上線&#xff0c;大科技方向資金關注更多。2025年8月6日龍虎榜行業方向分…

數據可視化發展歷程

數據可視化是數據描述的圖形表示&#xff0c;是當今數據分析發展最快速、最引人注目的領域之一。借助于可視化工具的發展&#xff0c;或樸實&#xff0c;或優雅&#xff0c;或絢爛的可視化作品給我們講述著各種數據故事。在這個領域中&#xff0c;科學、技術和藝術完美地結合在…

深入理解C++中的stack、queue和priority_queue

目錄 前言 1. stack&#xff08;棧&#xff09; 1.1 基本概念 1.2 常用接口 1.3 應用示例&#xff1a;最小棧 1.4 模擬實現 2. queue&#xff08;隊列&#xff09; 2.1 基本概念 2.2 常用接口 2.3 模擬實現 3. priority_queue&#xff08;優先隊列&#xff09; 3.1…

C++ 操作 Redis 客戶端

引言 前面幾篇文章都在介紹 Redis 原生命令行客戶端&#xff0c;在實際應用開發中&#xff0c;開發人員更希望使用針對特定編程語言的專用客戶端&#xff0c;通過編程的方式操作 Redis 數據庫。因此&#xff0c;Redis 支持多種編程語言。本文將介紹 如何使用 C 語言來操作 Red…

批量提問程序開發方案:基于Python的百度文小言接口實現

批量提問程序開發方案&#xff1a;基于Python的百度文小言接口實現 1. 項目概述 1.1 項目背景 在現代信息檢索和自動化辦公場景中&#xff0c;批量提問功能已成為提高工作效率的重要工具。本項目旨在開發一個基于Python的批量提問程序&#xff0c;專門針對百度文小言平臺&am…

Apollo中三種相機外參的可視化分析

Apollo中三種相機外參的可視化分析一、什么是相機外參&#xff1f;為什么需要可視化&#xff1f;二、不同外參來源對比三、詳細操作步驟1. 環境準備2. 獲取 NuScenes外參數據3. 外參到空間位置的轉換及可視化四、可視化對比1. NuScenes數據集外參2. Apollo BEV模型外參3. Apoll…

虛擬化KVM常用命令匯總

KVM&#xff08;Kernel-based Virtual Machine&#xff09;是一種開源的硬件虛擬化解決方案&#xff0c;它是 Linux 內核的一部分&#xff0c;允許在支持虛擬化技術的硬件&#xff08;如 Intel VT-x 或 AMD-V&#xff09;上運行虛擬機。KVM 將 Linux 內核轉變為一個裸機虛擬機監…

6s081環境配置以及使用vscode連接本地wsl2

6s081環境配置以及使用vscode連接wsl2 本人環境&#xff1a;windows11、wsl2ubuntu20.04 課程&#xff1a;6s081的2020版本的:https://pdos.csail.mit.edu/6.S081/2020/schedule.html 一、wsl2ubuntu20.04配置6s081環境 注&#xff1a;關于如何在window中安裝wsl&#xff0c;這…

C++實現線程池(3)緩存線程池

三. CachedThreadPool 的實現3.1 需求:動態調整線程數量&#xff1a;與 FixedThreadPool 不同&#xff0c;CachedThreadPool 的線程數量是動態調整的。當有新任務提交時&#xff0c;如果線程池中有空閑的線程&#xff0c;則會立即使用空閑線程執行任務&#xff1b;如果線程池中…

WMS+自動化立庫:無人倉的現在進行時

傳統倉庫正面臨嚴峻挑戰&#xff1a;效率瓶頸日益凸顯&#xff0c;人力成本持續攀升&#xff0c;空間利用率逼近極限&#xff0c;而訂單響應速度卻難以滿足市場需求。如何破局&#xff1f;WMS&#xff08;倉庫管理系統&#xff09;與自動化立體庫&#xff08;AS/RS&#xff09;…

多模態大模型研究每日簡報【2025-08-05】

訓練數據相關 EditGarment: An Instruction-Based Garment Editing Dataset Constructed with Automated MLLM Synthesis and Semantic-Aware Evaluation (https://arxiv.org/abs/2508.03497)&#xff1a;提出了一種自動化的流程&#xff0c;用于構建服裝編輯數據集EditGarmen…

4、docker數據卷管理命令 | docker volume

1、命令總覽命令作用出現頻率備注★ docker volume create新建卷高-d 指定驅動&#xff0c;-o 指定驅動選項★ docker volume ls列出卷高--filter danglingtrue 查孤兒卷★ docker volume inspect查看卷詳情高輸出 JSON&#xff0c;可加 --format★ docker volume rm刪除卷高只…

計數組合學7.14(對偶 RSK 算法)

7.14 對偶 RSK 算法 存在 RSK 算法的一種變體&#xff0c;其與乘積 ∏i,j(1xiyj)\prod_{i,j}(1 x_{i}y_{j})∏i,j?(1xi?yj?) 的關系類似于 RSK 算法本身與 ∏i,j(1?xiyj)?1\prod_{i,j}(1 - x_{i}y_{j})^{-1}∏i,j?(1?xi?yj?)?1 的關系。我們稱此變體為對偶 RSK 算法…

C語言中的進程、線程與進程間通信詳解

目錄 引言 基本概念 1. 進程&#xff08;Process&#xff09; 2. 線程&#xff08;Thread&#xff09; 線程編程實戰 1. 常見線程庫 2. 合理設置線程數 3. pthread 創建線程 線程同步機制 1. 互斥鎖 pthread_mutex_t 2. 條件變量 pthread_cond_t 3. 讀寫鎖 pthread…