最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot使用MyBatis Generator生成動(dòng)態(tài)SQL的詳細(xì)步驟

 更新時(shí)間:2025年06月20日 10:30:10   作者:惜鳥  
這篇文章主要介紹了SpringBoot使用MyBatis Generator生成動(dòng)態(tài)SQL的詳細(xì)步驟,我們將在Spring Boot項(xiàng)目中集成MyBatis Generator,并配置其生成MyBatis Dynamic SQL風(fēng)格的代碼,需要的朋友可以參考下

概述

我們將在Spring Boot項(xiàng)目中集成MyBatis Generator,并配置其生成MyBatis Dynamic SQL風(fēng)格的代碼。 MyBatis Dynamic SQL是MyBatis 3的一個(gè)特性,它允許使用Java API構(gòu)建動(dòng)態(tài)SQL查詢,避免編寫XML或使用Example類。

MyBatis Dynamic SQL 核心優(yōu)勢

  • 類型安全:所有列引用都是類型安全的
  • 流暢的API:鏈?zhǔn)秸{(diào)用構(gòu)建查詢
  • 動(dòng)態(tài)SQL:自然處理?xiàng)l件邏輯
  • 無XML:避免XML配置的繁瑣
  • IDE支持:自動(dòng)補(bǔ)全和類型檢查

步驟概述:

  • 創(chuàng)建Spring Boot項(xiàng)目,添加必要的依賴(包括MyBatis Spring Boot Starter、數(shù)據(jù)庫驅(qū)動(dòng)、MyBatis Generator等)。
  • 配置MyBatis Generator(通過Maven插件方式)。
  • 編寫generatorConfig.xml配置文件,指定生成Dynamic SQL風(fēng)格的代碼。
  • 運(yùn)行MyBatis Generator生成代碼。
  • 在Spring Boot中配置MyBatis,使用生成的Mapper。

詳細(xì)步驟

一、創(chuàng)建Spring Boot項(xiàng)目并添加依賴

使用Spring Initializr創(chuàng)建一個(gè)新項(xiàng)目,選擇以下依賴:

  • Spring Web (如果構(gòu)建Web應(yīng)用)
  • MyBatis Framework
  • MySQL Driver (以MySQL為例,或者根據(jù)你的數(shù)據(jù)庫選擇)

然后在pom.xml中添加MyBatis Generator Maven插件以及MyBatis Dynamic SQL依賴:

<dependencies>
    <!-- Spring Boot Starter -->
    <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>
    <!-- MySQL 驅(qū)動(dòng) -->
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <scope>runtime</scope>
    </dependency>
    <!-- Lombok -->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <!-- MyBatis Dynamic SQL -->
    <dependency>
        <groupId>org.mybatis.dynamic-sql</groupId>
        <artifactId>mybatis-dynamic-sql</artifactId>
        <version>1.5.0</version>
    </dependency>
</dependencies>

<build>
    <plugins>
        <!-- MyBatis Generator 插件 -->
        <plugin>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-maven-plugin</artifactId>
            <version>1.4.2</version>
            <dependencies>
                <dependency>
                    <groupId>com.mysql</groupId>
                    <artifactId>mysql-connector-j</artifactId>
                    <version>8.0.33</version>
                </dependency>
                <!-- 支持生成 Dynamic SQL -->
                <dependency>
                    <groupId>org.mybatis.dynamic-sql</groupId>
                    <artifactId>mybatis-dynamic-sql</artifactId>
                    <version>1.5.0</version>
                </dependency>
            </dependencies>
            <configuration>
                <configurationFile>src/main/resources/generatorConfig.xml</configurationFile>
                <overwrite>true</overwrite>
                <verbose>true</verbose>
            </configuration>
        </plugin>
    </plugins>
</build>

二、編寫generatorConfig.xml配置文件

src/main/resources目錄下創(chuàng)建generatorConfig.xml文件。我們需要配置生成Dynamic SQL風(fēng)格的代碼,這通過設(shè)置targetRuntime="MyBatis3DynamicSql"來實(shí)現(xiàn)。

示例配置:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "https://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
    <!-- 引入 application.properties 中的配置(可選) -->
    <properties resource="application.properties"/>

    <!-- 數(shù)據(jù)庫驅(qū)動(dòng)路徑(如果未通過Maven依賴管理) -->
    <!-- <classPathEntry location="/path/to/mysql-connector-java-8.0.33.jar"/> -->

    <context id="mysql" targetRuntime="MyBatis3DynamicSql">
        <!-- 生成的Java文件編碼 -->
        <property name="javaFileEncoding" value="UTF-8"/>

        <!-- 生成的Java文件的注釋 -->
        <commentGenerator>
            <!-- 注釋配置:不生成注釋 -->
            <property name="suppressAllComments" value="true"/>
            <!-- 生成注釋 -->
            <!--            <property name="addRemarkComments" value="true"/>-->
        </commentGenerator>
        <!-- 數(shù)據(jù)庫連接信息 -->
        <jdbcConnection driverClass="${spring.datasource.driver-class-name}"
                        connectionURL="${spring.datasource.url}"
                        userId="${spring.datasource.username}"
                        password="${spring.datasource.password}">
        </jdbcConnection>
        <!-- Java模型生成配置 -->
        <javaModelGenerator targetPackage="com.example.demo.model.entity" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <!-- 注意:如果使用Dynamic SQL方式,不需要XML映射文件 -->
        <!-- 生成 SQL Map XML 文件的配置 -->
        <!--        <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">-->
        <!--            <property name="enableSubPackages" value="true" />-->
        <!--        </sqlMapGenerator>-->
        <!-- Mapper接口生成配置 -->
        <javaClientGenerator type="ANNOTATEDMAPPER"
                             targetPackage="com.example.demo.repository.generated"
                             targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>
        <!-- 指定要生成的表 -->
        <table tableName="user" domainObjectName="User">
            <generatedKey column="id" sqlStatement="MySql" identity="true"/>
        </table>
        <table tableName="rule" domainObjectName="RuleEntity" mapperName="RuleMapper">
            <generatedKey column="id" sqlStatement="MySql" identity="true"/>
        </table>

        <table tableName="rule_version" domainObjectName="RuleVersionEntity" mapperName="RuleVersionMapper">
            <generatedKey column="id" sqlStatement="MySql" identity="true"/>
        </table>
        <!-- 生成所有表 -->
        <!--         <table tableName="%" />-->
    </context>
</generatorConfiguration>


注意:

  • 我們使用了targetRuntime="MyBatis3DynamicSql",這會(huì)生成Dynamic SQL風(fēng)格的代碼。
  • 不需要配置sqlMapGenerator,因?yàn)镈ynamic SQL不生成XML映射文件。
  • javaClientGeneratortype設(shè)置為ANNOTATEDMAPPER,表示使用注解方式(實(shí)際上Dynamic SQL的Mapper接口是通過Java API構(gòu)建的,由Dynamic SQL的運(yùn)行時(shí)庫提供支持)。
  • jdbcConnection中,我們使用了Spring Boot的application.properties中的數(shù)據(jù)庫配置(通過${}占位符引用)。需要在generatorConfig.xml文件中配置 <properties resource="application.properties"/>,并且確保application.properties中有這些屬性。

三、配置application.properties

src/main/resources/application.properties中配置數(shù)據(jù)源:

spring.application.name=demo
server.port=8088
# 數(shù)據(jù)源配置
spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase
spring.datasource.username=root
spring.datasource.password=mysecretpassword
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

四、運(yùn)行MyBatis Generator生成代碼

在項(xiàng)目根目錄下運(yùn)行命令:

mvn mybatis-generator:generate

或者在IDE中運(yùn)行Maven插件的mybatis-generator:generate目標(biāo)。

生成的文件將包括:

  • 實(shí)體類(POJO):在com.example.demo.model.entity包下。
  • Mapper接口:在com.example.demo.repository.generated包下。注意,生成的Mapper接口會(huì)繼承MyBatis Dynamic SQL提供的MyBatis3Mapper接口(比如CommonCountMapper, CommonDeleteMapper, CommonUpdateMapper),這些接口提供了一些基本的CRUD方法。

五、在Spring Boot中使用生成的Mapper

  • 在目錄 com.example.demo.config 創(chuàng)建 MyBatisConfig.java 配置類:
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

@Configuration
@MapperScan("com.example.demo.repository")
public class MyBatisConfig {
    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        sessionFactory.setTypeAliasesPackage("com.example.demo.model.entity");

        return sessionFactory.getObject();
    }

}

在Spring Boot項(xiàng)目中,使用@MapperScan注解可以方便地掃描并注冊MyBatis的Mapper接口。這樣,我們就不需要在每個(gè)Mapper接口上都添加@Mapper注解。

注意事項(xiàng):

  • @MapperScan@Mapper:如果使用了@MapperScan,則不需要在每個(gè)Mapper接口上再寫@Mapper。但是,如果有些Mapper接口不在掃描路徑下,那么仍然需要在該接口上使用@Mapper。
  • 包路徑:確保@MapperScan指定的包路徑正確,否則Spring容器無法創(chuàng)建Mapper的Bean,導(dǎo)致注入失敗。
  • 多模塊項(xiàng)目:如果項(xiàng)目有多個(gè)模塊,并且Mapper接口分布在不同的模塊中,確保這些模塊的包路徑都被掃描到。

在Service中注入Mapper并使用:

@Service
@RequiredArgsConstructor
public class UserService {
    
    private final UserMapper userMapper;
    
    // 創(chuàng)建用戶
    public int createUser(User user) {
        return userMapper.insert(user);
    }
    
    // 根據(jù)ID獲取用戶
    public Optional<User> getUserById(Long id) {
        return userMapper.selectByPrimaryKey(id);
    }
    
    // 更新用戶
    public int updateUser(User user) {
        return userMapper.updateByPrimaryKeySelective(user);
    }
    
    // 刪除用戶
    public int deleteUser(Long id) {
        return userMapper.deleteByPrimaryKey(id);
    }
    
    // 動(dòng)態(tài)查詢用戶
    public List<User> findUsers(String username, Integer minAge, Integer maxAge) {
        return userMapper.select(c -> c
            .where(UserDynamicSqlSupport.username, isLikeIfPresent(username).map(s -> s + "%")
            .and(UserDynamicSqlSupport.age, isBetweenWhenPresent(minAge, maxAge))
            .orderBy(UserDynamicSqlSupport.createTime.descending())
            .build()
            .execute());
    }
    
    // 輔助方法:條件存在時(shí)使用 LIKE
    private Optional<Condition> isLikeIfPresent(String value) {
        return Optional.ofNullable(value)
            .filter(v -> !v.isEmpty())
            .map(v -> UserDynamicSqlSupport.username.like(v));
    }
    
    // 輔助方法:條件存在時(shí)使用 BETWEEN
    private Optional<BetweenCondition> isBetweenWhenPresent(Integer min, Integer max) {
        if (min != null && max != null) {
            return Optional.of(UserDynamicSqlSupport.age.between(min, max));
        }
        return Optional.empty();
    }
}

注意:上面的user是一個(gè)自動(dòng)生成的表對應(yīng)的對象(在UserMapper中有一個(gè)靜態(tài)字段user,用于構(gòu)建查詢)。實(shí)際使用時(shí),需要導(dǎo)入生成的Mapper和表對象。

例如,在UserService中導(dǎo)入:

import static com.example.demo.mapper.UserDynamicSqlSupport.*;

import static org.mybatis.dynamic.sql.SqlBuilder.*;

  • 在controller中注入service并使用
@RestController
@RequestMapping("/api/users")
@RequiredArgsConstructor
public class UserController {
    
    private final UserService userService;
    
    @PostMapping
    public ResponseEntity<?> createUser(@RequestBody User user) {
        int result = userService.createUser(user);
        return result > 0 
            ? ResponseEntity.ok("User created")
            : ResponseEntity.badRequest().body("Create failed");
    }
    
    @GetMapping("/{id}")
    public ResponseEntity<User> getUser(@PathVariable Long id) {
        return userService.getUserById(id)
            .map(ResponseEntity::ok)
            .orElse(ResponseEntity.notFound().build());
    }
    
    @PutMapping("/{id}")
    public ResponseEntity<?> updateUser(@PathVariable Long id, @RequestBody User user) {
        user.setId(id);
        int result = userService.updateUser(user);
        return result > 0 
            ? ResponseEntity.ok("User updated")
            : ResponseEntity.badRequest().body("Update failed");
    }
    
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteUser(@PathVariable Long id) {
        int result = userService.deleteUser(id);
        return result > 0 
            ? ResponseEntity.ok("User deleted")
            : ResponseEntity.badRequest().body("Delete failed");
    }
    
    @GetMapping("/search")
    public List<User> searchUsers(
            @RequestParam(required = false) String username,
            @RequestParam(required = false) Integer minAge,
            @RequestParam(required = false) Integer maxAge) {
        
        return userService.findUsers(username, minAge, maxAge);
    }
}

六、MyBatis Dynamic SQL 生成代碼的特點(diǎn)

生成的Mapper接口包含的方法:

  • insert:插入記錄
  • insertMultiple:批量插入
  • insertSelective:選擇性插入(忽略null)
  • selectByPrimaryKey:根據(jù)主鍵查詢
  • select:根據(jù)條件查詢(可返回多條)
  • selectOne:根據(jù)條件查詢一條
  • update:更新
  • delete:刪除

同時(shí)會(huì)生成一個(gè)與表同名的輔助類(如UserDynamicSqlSupport),其中包含表的列定義,用于構(gòu)建動(dòng)態(tài)SQL。

不需要XML映射文件,所有SQL通過Java API動(dòng)態(tài)構(gòu)建。

七、注意事項(xiàng)

  • 確保數(shù)據(jù)庫表有主鍵,否則生成代碼時(shí)可能會(huì)出現(xiàn)問題。
  • 如果表名或列名是SQL關(guān)鍵字,需要在配置中使用<columnOverride><table>delimitIdentifiers屬性處理。
  • 生成的代碼可能會(huì)覆蓋已有的文件,注意備份自定義代碼(通常不要修改生成的代碼,而是通過擴(kuò)展方式)。

八、總結(jié)

本方案在 Spring Boot 中集成了 MyBatis Generator,并配置生成 MyBatis Dynamic SQL 風(fēng)格的代碼,具有以下特點(diǎn):

  • 代碼簡潔:使用 Lombok 減少樣板代碼
  • 類型安全:Dynamic SQL 提供編譯時(shí)檢查
  • 易于維護(hù):無需 XML 配置
  • 動(dòng)態(tài)查詢:靈活構(gòu)建復(fù)雜查詢
  • 高效開發(fā):自動(dòng)生成基礎(chǔ) CRUD 代碼

通過這種方式,你可以專注于業(yè)務(wù)邏輯開發(fā),而無需手動(dòng)編寫重復(fù)的數(shù)據(jù)訪問層代碼。

以上就是SpringBoot使用MyBatis Generator生成動(dòng)態(tài)SQL的詳細(xì)步驟的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot生成動(dòng)態(tài)SQL的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • IntelliJ IDEA 2020.3.3現(xiàn)已發(fā)布!新增“受信任項(xiàng)目”功能

    IntelliJ IDEA 2020.3.3現(xiàn)已發(fā)布!新增“受信任項(xiàng)目”功能

    這篇文章主要介紹了IntelliJ IDEA 2020.3.3現(xiàn)已發(fā)布!新增“受信任項(xiàng)目”功能,本文給大家分享了idea2020.3.3激活碼的詳細(xì)破解教程,每種方法都很好用,使用idea2020.3以下所有版本,需要的朋友可以參考下
    2021-03-03
  • 使用SpringBoot實(shí)現(xiàn)Redis多數(shù)據(jù)庫緩存

    使用SpringBoot實(shí)現(xiàn)Redis多數(shù)據(jù)庫緩存

    在我的系統(tǒng)中,為了優(yōu)化用戶行為數(shù)據(jù)的存儲(chǔ)與訪問效率,我引入了Redis緩存,并將數(shù)據(jù)分布在不同的Redis數(shù)據(jù)庫中,通過這種方式,可以減少單一數(shù)據(jù)庫的負(fù)載,提高系統(tǒng)的整體性能,所以本文給大家介紹了使用SpringBoot實(shí)現(xiàn)Redis多數(shù)據(jù)庫緩存,需要的朋友可以參考下
    2024-06-06
  • Java中的CompletableFuture原理與用法

    Java中的CompletableFuture原理與用法

    CompletableFuture 是由Java8引入的,這讓我們編寫清晰可讀的異步代碼變得更加容易,該類功能比Future 更加強(qiáng)大,在Java中CompletableFuture用于異步編程,異步通常意味著非阻塞,運(yùn)行任務(wù)單獨(dú)的線程,與主線程隔離,這篇文章介紹CompletableFuture原理與用法,一起看看吧
    2024-01-01
  • Intellij IDEA十大快捷鍵

    Intellij IDEA十大快捷鍵

    Intellij IDEA中有很多快捷鍵讓人愛不釋手,stackoverflow上也有一些有趣的討論.這篇文章主要介紹了Intellij IDEA十大快捷鍵,需要的朋友可以參考下
    2018-03-03
  • springboot解決java.lang.ArrayStoreException異常

    springboot解決java.lang.ArrayStoreException異常

    這篇文章介紹了springboot解決java.lang.ArrayStoreException異常的方法,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-12-12
  • Java利用Jsoup解析和操作HTML的技術(shù)指南

    Java利用Jsoup解析和操作HTML的技術(shù)指南

    在現(xiàn)代 Java 開發(fā)中,處理 HTML 數(shù)據(jù)是一項(xiàng)常見需求,無論是抓取網(wǎng)頁數(shù)據(jù)、解析 HTML 文檔,還是操作 DOM 樹,Jsoup 都是一個(gè)強(qiáng)大的工具,本文將介紹 Jsoup 的基本功能,并通過多個(gè)詳細(xì)的代碼示例展示如何使用它解析和操作 HTML,需要的朋友可以參考下
    2025-03-03
  • Springboot中PropertySource的結(jié)構(gòu)與加載過程逐步分析講解

    Springboot中PropertySource的結(jié)構(gòu)與加載過程逐步分析講解

    本文重點(diǎn)講解一下Spring中@PropertySource注解的使用,PropertySource主要是對屬性源的抽象,包含屬性源名稱name和屬性源內(nèi)容對象source。其方法主要是對這兩個(gè)字段進(jìn)行操作
    2023-01-01
  • SpringBoot接口獲取參數(shù)的常用注解詳解

    SpringBoot接口獲取參數(shù)的常用注解詳解

    SpringBoot 接口獲取參數(shù)的注解非常豐富,這篇文章主要為大家詳細(xì)介紹了一些常用參數(shù)注解的使用,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解下
    2026-01-01
  • MyBatis中基于別名typeAliases的設(shè)置

    MyBatis中基于別名typeAliases的設(shè)置

    這篇文章主要介紹了MyBatis中基于別名typeAliases的設(shè)置,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-07-07
  • Java判斷字符串是否是整數(shù)或者浮點(diǎn)數(shù)的方法

    Java判斷字符串是否是整數(shù)或者浮點(diǎn)數(shù)的方法

    今天小編就為大家分享一篇Java判斷字符串是否是整數(shù)或者浮點(diǎn)數(shù)的方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-07-07

最新評論

弥勒县| 会泽县| 滁州市| 霍州市| 沙洋县| 哈尔滨市| 门源| 杨浦区| 家居| 哈尔滨市| 永胜县| 靖安县| 宝应县| 石台县| 大悟县| 从化市| 汝阳县| 南安市| 南城县| 昔阳县| 三河市| 玛纳斯县| 和林格尔县| 长葛市| 攀枝花市| 重庆市| 天长市| 怀集县| 永济市| 巨野县| 合作市| 台北县| 当阳市| 奈曼旗| 墨玉县| 凤冈县| 景谷| 涪陵区| 行唐县| 邹平县| 旅游|