欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Spring Boot 集成 MyBatis 全攻略(最新整理)

 更新時間:2025年08月18日 10:14:37   作者:柯南二號  
本文詳解SpringBoot集成MyBatis的流程,涵蓋依賴配置、數(shù)據(jù)源設(shè)置、實體類與Mapper編寫(注解/XML)、Service/Controller開發(fā)及分頁、緩存、動態(tài)SQL等優(yōu)化,助力建設(shè)高效全棧應(yīng)用,感興趣的朋友跟隨小編一起看看吧

Spring Boot 集成 MyBatis 全攻略

1. 為什么選擇 MyBatis

  • ORM 靈活性:相比 Hibernate,MyBatis 更靈活,SQL 可控,性能優(yōu)化空間大。
  • 學(xué)習(xí)曲線低:對于熟悉 SQL 的開發(fā)者,上手快。
  • 與 Spring Boot 無縫整合:只需少量配置,即可快速使用。

2. 基礎(chǔ)環(huán)境

依賴(pom.xml)

<dependencies>
    <!-- Spring Boot Web -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- MyBatis-Spring-Boot-Starter -->
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>3.0.3</version>
    </dependency>
    <!-- 數(shù)據(jù)庫驅(qū)動 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <scope>runtime</scope>
    </dependency>
    <!-- Lombok(可選) -->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
</dependencies>

3. 配置數(shù)據(jù)源

application.yml

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/demo_db?useSSL=false&serverTimezone=Asia/Shanghai
    username: root
    password: root123
    driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
  # 指定 Mapper XML 文件位置
  mapper-locations: classpath:mapper/*.xml
  # 指定實體類包,自動映射列名和屬性名(開啟駝峰命名)
  type-aliases-package: com.example.demo.entity
  configuration:
    map-underscore-to-camel-case: true

4. 定義實體類

package com.example.demo.entity;
import lombok.Data;
@Data
public class User {
    private Long id;
    private String username;
    private String email;
}

5. 定義 Mapper 接口

package com.example.demo.mapper;
import com.example.demo.entity.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
@Mapper
public interface UserMapper {
    @Select("SELECT * FROM user WHERE id = #{id}")
    User findById(Long id);
    @Select("SELECT * FROM user")
    List<User> findAll();
    @Insert("INSERT INTO user(username, email) VALUES(#{username}, #{email})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(User user);
    @Update("UPDATE user SET username=#{username}, email=#{email} WHERE id=#{id}")
    int update(User user);
    @Delete("DELETE FROM user WHERE id=#{id}")
    int delete(Long id);
}

? 這里用注解方式,簡單清晰;復(fù)雜 SQL 可以寫到 XML 文件。

6. 使用 XML 配置 SQL(適合復(fù)雜 SQL)

resources/mapper/UserMapper.xml 中:

<?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="com.example.demo.mapper.UserMapper">
    <select id="findAll" resultType="com.example.demo.entity.User">
        SELECT * FROM user
    </select>
    <insert id="insert" parameterType="com.example.demo.entity.User" useGeneratedKeys="true" keyProperty="id">
        INSERT INTO user(username, email) VALUES(#{username}, #{email})
    </insert>
</mapper>

7. Service + Controller

Service

package com.example.demo.service;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserService {
    private final UserMapper userMapper;
    public UserService(UserMapper userMapper) {
        this.userMapper = userMapper;
    }
    public User getUser(Long id) {
        return userMapper.findById(id);
    }
    public List<User> listUsers() {
        return userMapper.findAll();
    }
    public int addUser(User user) {
        return userMapper.insert(user);
    }
}

Controller

package com.example.demo.controller;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/users")
public class UserController {
    private final UserService userService;
    public UserController(UserService userService) {
        this.userService = userService;
    }
    @GetMapping("/{id}")
    public User getUser(@PathVariable Long id) {
        return userService.getUser(id);
    }
    @GetMapping
    public List<User> listUsers() {
        return userService.listUsers();
    }
    @PostMapping
    public String addUser(@RequestBody User user) {
        userService.addUser(user);
        return "User added successfully!";
    }
}

8. 分頁支持

推薦集成 PageHelper 插件:

<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.4.7</version>
</dependency>

使用:

PageHelper.startPage(1, 10);
List<User> users = userMapper.findAll();
PageInfo<User> pageInfo = new PageInfo<>(users);

9. 常見優(yōu)化

  1. 批量插入:使用 foreach 標(biāo)簽。
  2. 動態(tài) SQL:使用 <if> <choose> 等標(biāo)簽構(gòu)建靈活查詢。
  3. 二級緩存<cache/> 配置 + Redis 集成。
  4. 多數(shù)據(jù)源:Spring Boot + MyBatis 支持動態(tài)數(shù)據(jù)源切換。
  5. 統(tǒng)一異常處理:結(jié)合 @ControllerAdvice 統(tǒng)一返回接口錯誤信息。

10. 總結(jié)

Spring Boot + MyBatis 集成流程大致分為:

  1. 加依賴 → 2. 配數(shù)據(jù)源 → 3. 寫實體類 → 4. 寫 Mapper(注解/XML) → 5. 寫 Service/Controller → 6. 增強功能(分頁、緩存、動態(tài) SQL)。

這樣,就能快速搭建一個 基于 Spring Boot + MyBatis 的全棧開發(fā)框架 ??。

到此這篇關(guān)于Spring Boot 集成 MyBatis 全攻略(最新整理)的文章就介紹到這了,更多相關(guān)Spring Boot 集成 MyBatis內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Java數(shù)據(jù)庫存儲數(shù)組的方法小結(jié)

    Java數(shù)據(jù)庫存儲數(shù)組的方法小結(jié)

    在現(xiàn)代軟件開發(fā)中,數(shù)組是常用的數(shù)據(jù)結(jié)構(gòu)之一,然而,在關(guān)系數(shù)據(jù)庫中直接存儲數(shù)組并不是一個簡單的任務(wù),本文將詳細介紹幾種在Java中將數(shù)組存儲到數(shù)據(jù)庫的方法,包括使用JPA、JSON、XML、以及關(guān)系型數(shù)據(jù)庫的數(shù)組類型等,需要的朋友可以參考下
    2024-09-09
  • 詳解SpringBoot結(jié)合swagger2快速生成簡單的接口文檔

    詳解SpringBoot結(jié)合swagger2快速生成簡單的接口文檔

    這篇文章主要介紹了詳解SpringBoot結(jié)合swagger2快速生成簡單的接口文檔,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2019-05-05
  • Sentinel 整合SpringCloud的詳細教程

    Sentinel 整合SpringCloud的詳細教程

    Spring Cloud Alibaba Sentinel 是阿里巴巴提供的,致力于提供微服務(wù)一站式解決方案,這篇文章主要介紹了Sentinel 之 整合SpringCloud的相關(guān)知識,需要的朋友可以參考下
    2021-10-10
  • Java concurrency之LockSupport_動力節(jié)點Java學(xué)院整理

    Java concurrency之LockSupport_動力節(jié)點Java學(xué)院整理

    這篇文章主要為大家詳細介紹了Java concurrency之LockSupport的相關(guān)資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-06-06
  • SpringBoot中TransactionTemplate事務(wù)管理的實現(xiàn)

    SpringBoot中TransactionTemplate事務(wù)管理的實現(xiàn)

    Spring Boot提供了多種方式來管理事務(wù),其中之一是使用TransactionTemplate,本文主要介紹了SpringBoot中TransactionTemplate事務(wù)管理的實現(xiàn),具有一定的參考價值,感興趣的可以了解一下
    2024-04-04
  • java中Map集合的常用方法總結(jié)大全

    java中Map集合的常用方法總結(jié)大全

    開發(fā)中最常用的就是List集合和Map集合,Map集合是基于java核心類java.util中的,下面這篇文章主要給大家總結(jié)介紹了關(guān)于java中Map集合的一些常用方法,文中通過代碼介紹的非常詳細,需要的朋友可以參考下
    2024-01-01
  • Java實現(xiàn)視頻格式轉(zhuǎn)換的完整指南

    Java實現(xiàn)視頻格式轉(zhuǎn)換的完整指南

    在Java中實現(xiàn)視頻格式的轉(zhuǎn)換,通常需要借助第三方工具或庫,因為視頻的編解碼操作復(fù)雜且性能需求較高,以下是實現(xiàn)視頻格式轉(zhuǎn)換的常用方法和步驟,需要的朋友可以參考下
    2025-05-05
  • 細數(shù)Java接口的概念、分類及與抽象類的區(qū)別

    細數(shù)Java接口的概念、分類及與抽象類的區(qū)別

    下面小編就為大家?guī)硪黄殧?shù)Java接口的概念、分類及與抽象類的區(qū)別。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2016-11-11
  • spring?@Primary-在spring中的使用方式

    spring?@Primary-在spring中的使用方式

    這篇文章主要介紹了spring?@Primary-在spring中的使用方式,具有很好的參考價值,希望對大家有所幫助。
    2022-01-01
  • Mybatis操作多數(shù)據(jù)源的實現(xiàn)

    Mybatis操作多數(shù)據(jù)源的實現(xiàn)

    本文主要介紹了Mybatis操作多數(shù)據(jù)源,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-05-05

最新評論