主頁 > 後端開發 > SpringBoot與MyBatis零XML配置集成和集成測驗

SpringBoot與MyBatis零XML配置集成和集成測驗

2023-07-09 07:48:03 後端開發

原文地址:https://ntopic.cn/p/2023070801/

源代碼先行:

  • Gitee本文介紹的完整倉庫:https://gitee.com/obullxl/ntopic-boot
  • GitHub本文介紹的完整倉庫:https://github.com/obullxl/ntopic-boot

背景介紹

在Java眾多的ORM框架里面,MyBatis是比較輕量級框架之一,既有資料表和Java物件映射功能,在SQL撰寫方面又不失原生SQL的特性,SpringBoot提倡使用注解代替XML配置,同樣的,在集成MyBatis時也可以做到全注解化,無XML配置,相關的集成方法網上存在大量的教程,本文是個人在實際專案程序的一個備忘,并不是復制和粘貼,同時在本文后面提供了完整的集成測驗用例,

MyBatis集成

涉及到以下4個方面:

  • 我們Maven工程是一個SpringBoot工程
  • 引入MyBatis的Starter依賴
  • SpringBoot工程配置中增加MyBatis的配置
  • Mapper/DAO通過注解實作

SpringBoot工程依賴

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.3</version>
        <relativePath/>
    </parent>

  <!-- 其他部分省略 -->
</project>

MyBatis Starter依賴

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <!-- 其他省略 -->
      <dependencyManagement>
        <dependencies>
          <!-- MyBatis -->
          <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>2.2.0</version>
            </dependency>

          <!-- MySQL -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.26</version>
            </dependency>

          <!-- SQLite -->
            <dependency>
                <groupId>org.xerial</groupId>
                <artifactId>sqlite-jdbc</artifactId>
                <version>3.39.2.0</version>
                <scope>provided</scope>
            </dependency>

            <!-- Druid -->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>1.1.2</version>
            </dependency>
          
          <!-- 其他省略 -->
          
        </dependencies>
      </dependencyManagement>
  <!-- 其他省略 -->
</project>

SpringBoot Main配置

  • application.properties配置,增加DB資料源:
#
# 資料庫:url值設定成自己的檔案路徑
#
ntopic.datasource.driver-class-name=org.sqlite.JDBC
ntopic.datasource.url=jdbc:sqlite:./../NTopicBoot.sqlite
ntopic.datasource.userName=
ntopic.datasource.password=
  • MapperScan注解:指明MyBatis的Mapper在哪寫包中,cn.ntopic.das..**.dao指明,我們的Mapper類所在的包
/**
 * Author: [email protected]
 * Copyright (c) 2020-2021 All Rights Reserved.
 */
package cn.ntopic;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.Configuration;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.support.TransactionTemplate;

import javax.sql.DataSource;

/**
 * NTopic啟動器
 *
 * @author obullxl 2021年06月05日: 新增
 */
@SpringBootApplication
@MapperScan(basePackages = "cn.ntopic.das..**.dao", sqlSessionFactoryRef = "ntSqlSessionFactory")
public class NTBootApplication {

    /**
     * SpringBoot啟動
     */
    public static void main(String[] args) {
        SpringApplication.run(NTBootApplication.class, args);
    }

    /**
     * DataSource配置
     */
    @Bean(name = "ntDataSource", initMethod = "init", destroyMethod = "close")
    public DruidDataSource ntDataSource(@Value("${ntopic.datasource.url}") String url
            , @Value("${ntopic.datasource.userName}") String userName
            , @Value("${ntopic.datasource.password}") String password) {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(url);
        dataSource.setUsername(userName);
        dataSource.setPassword(password);

        dataSource.setInitialSize(0);
        dataSource.setMinIdle(1);
        dataSource.setMaxActive(5);
        dataSource.setMaxWait(3000L);

        return dataSource;
    }

    /**
     * MyBatis事務配置
     */
    @Bean("ntSqlSessionFactory")
    public SqlSessionFactoryBean ntSqlSessionFactory(@Qualifier("ntDataSource") DataSource dataSource) {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);

        Configuration configuration = new Configuration();
        configuration.setMapUnderscoreToCamelCase(true);
        sqlSessionFactoryBean.setConfiguration(configuration);

        return sqlSessionFactoryBean;
    }

    /** 其他代碼省略 */
}

MyBatis Mapper類/DAO類

幾個核心的注解:

  • Insert插入
  • Select查詢
  • Update更新
  • Delete洗掉
/**
 * Author: [email protected]
 * Copyright (c) 2020-2021 All Rights Reserved.
 */
package cn.ntopic.das.dao;

import cn.ntopic.das.model.UserBaseDO;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.List;

/**
 * @author obullxl 2021年10月17日: 新增
 */
@Repository("userBaseDAO")
public interface UserBaseDAO {

    /**
     * 新增用戶記錄
     */
    @Insert("INSERT INTO nt_user_base (id, name, password, role_list, ext_map, create_time, modify_time)" +
            " VALUES (#{id,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, #{roleList,jdbcType=VARCHAR}, #{extMap,jdbcType=VARCHAR}, #{createTime,jdbcType=TIMESTAMP}, #{modifyTime,jdbcType=TIMESTAMP})")
    void insert(UserBaseDO userBaseDO);

    /**
     * 根據ID查詢記錄
     */
    @Select("SELECT * FROM nt_user_base WHERE id = #{id,jdbcType=VARCHAR}")
    UserBaseDO selectById(@Param("id") String id);

    /**
     * 根據名稱查詢記錄
     */
    @Select("SELECT * FROM nt_user_base WHERE name = #{name,jdbcType=VARCHAR}")
    UserBaseDO selectByName(@Param("name") String name);

    /**
     * 查詢所有用戶
     */
    @Select("SELECT * FROM nt_user_base LIMIT 30")
    List<UserBaseDO> select();

    /**
     * 更新角色串列
     * FIXME: SQLite/MySQL 當前時間函式不一致,本次通過入參傳入!
     */
    @Update("UPDATE nt_user_base SET modify_time=#{modifyTime,jdbcType=TIMESTAMP}, role_list=#{roleList,jdbcType=VARCHAR} WHERE id=#{id,jdbcType=VARCHAR}")
    int updateRoleList(@Param("id") String id, @Param("modifyTime") Date modifyTime, @Param("roleList") String roleList);

    /**
     * 洗掉用戶記錄
     */
    @Delete("DELETE FROM nt_user_base WHERE id = #{id,jdbcType=VARCHAR}")
    int deleteById(@Param("id") String id);

    /**
     * 洗掉用戶記錄
     */
    @Delete("DELETE FROM nt_user_base WHERE name = #{name,jdbcType=VARCHAR}")
    int deleteByName(@Param("name") String name);

}

集成測驗(包括CRUD操作)

/**
 * Author: [email protected]
 * Copyright (c) 2020-2021 All Rights Reserved.
 */
package cn.ntopic.das.dao;

import cn.ntopic.das.model.UserBaseDO;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.Date;

/**
 * @author obullxl 2021年10月17日: 新增
 */
@SpringBootTest
@RunWith(SpringRunner.class)
public class UserBaseDAOTest extends AbstractJUnit4SpringContextTests {

    @Autowired
    @Qualifier("userBaseDAO")
    private UserBaseDAO userBaseDAO;

    /**
     * CRUD簡單測驗
     */
    @Test
    public void test_insert_select_update_delete() {
        final String id = "ID-" + RandomUtils.nextLong();
        final String name = "NAME-" + RandomUtils.nextLong();

        // 1. 清理資料
        this.userBaseDAO.deleteById(id);
        this.userBaseDAO.deleteByName(name);

        // 請求資料 - 驗證
        UserBaseDO userBaseDO = this.userBaseDAO.selectById(id);
        Assert.assertNull(userBaseDO);

        userBaseDO = this.userBaseDAO.selectByName(name);
        Assert.assertNull(userBaseDO);

        try {
            // 2. 新增資料
            UserBaseDO newUserDO = new UserBaseDO();
            newUserDO.setId(id);
            newUserDO.setName(name);
            newUserDO.setCreateTime(new Date());
            newUserDO.setModifyTime(new Date());
            this.userBaseDAO.insert(newUserDO);

            // 3. 資料查詢 - 新增驗證
            UserBaseDO checkUserDO = this.userBaseDAO.selectById(id);
            Assert.assertNotNull(checkUserDO);
            Assert.assertEquals(name, checkUserDO.getName());
            Assert.assertNotNull(checkUserDO.getCreateTime());
            Assert.assertNotNull(checkUserDO.getModifyTime());
            Assert.assertTrue(StringUtils.isBlank(checkUserDO.getRoleList()));

            // 4. 更新資料
            int update = this.userBaseDAO.updateRoleList(id, new Date(), "ADMIN,DATA");
            Assert.assertEquals(1, update);

            // 更新資料 - 驗證
            checkUserDO = this.userBaseDAO.selectById(id);
            Assert.assertNotNull(checkUserDO);
            Assert.assertEquals("ADMIN,DATA", checkUserDO.getRoleList());

            // 5. 資料洗掉
            int delete = this.userBaseDAO.deleteById(id);
            Assert.assertEquals(1, delete);

            delete = this.userBaseDAO.deleteByName(name);
            Assert.assertEquals(0, delete);
        } finally {
            // 清理資料
            this.userBaseDAO.deleteById(id);
        }
    }
}

本文作者:奔跑的蝸牛,轉載請注明原文鏈接:https://ntopic.cn

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/556839.html

標籤:其他

上一篇:從零用python flask框架寫一個簡易的網站

下一篇:返回列表

標籤雲
其他(162247) Python(38272) JavaScript(25528) Java(18293) C(15239) 區塊鏈(8275) C#(7972) AI(7469) 爪哇(7425) MySQL(7291) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5876) 数组(5741) R(5409) Linux(5347) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4614) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2438) ASP.NET(2404) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) HtmlCss(1993) .NET技术(1986) 功能(1967) Web開發(1951) C++(1942) python-3.x(1918) 弹簧靴(1913) xml(1889) PostgreSQL(1882) .NETCore(1863) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • SpringBoot與MyBatis零XML配置集成和集成測驗

    Java存在很多ORM框架,MyBaits框架是我們專案中使用得最多也是最愿意推薦的框架,它既有資料表和Java物件映射功能,又有原生SQL的特性。在與SpringBoot集成上,和其他框架一樣,可以做到全注解化,無XML配置…… ......

    uj5u.com 2023-07-09 07:48:03 more
  • 從零用python flask框架寫一個簡易的網站

    要用Python寫一個網站,你可以使用Python的Web框架來開發。常見的Python Web框架包括Django、Flask、Bottle等。以下是一個簡單的使用Flask框架開發的示例。 ### 1. 安裝Flask 在開始開發之前,你需要安裝Flask框架。你可以使用以下命令來安裝: ``` ......

    uj5u.com 2023-07-09 07:47:59 more
  • python中zeros函式和ones函式的詳細用法

    在使用Python進行資料分析和科學計算時,經常需要創建和操作多維陣列。NumPy是Python中一個常見的數學庫,它提供了許多方便的函式來創建、操作和處理多維陣列。 NumPy中常用的兩個函式是zeros()函式和ones()函式。這些函式可以幫助我們快速創建特定維度和形狀的多維陣列,并設定初始值 ......

    uj5u.com 2023-07-09 07:46:49 more
  • springboot整合rabbitMQ

    ## 1.生產者工程 - pom.xml里引入依賴 ~~~xml org.springframework.boot spring-boot-starter-amqp ~~~ - application.yml里配置基本資訊 ~~~yaml spring: rabbitmq: host: localh ......

    uj5u.com 2023-07-09 07:46:45 more
  • 【7月最新實作】使用Python獲取全網招聘資料,實作可視化分析

    哈嘍兄弟們,今天來實作采集一下最新的qcwu招聘資料。因為網站嘛,大家都爬來爬去的,人家就會經常更新,所以代碼對應的也要經常重新去寫。 對于會的人來說,當然無所謂,任他更新也攔不住,但是對于不會的小伙伴來說,網站一更新,當場自閉。 所以這期是出給不會的小伙伴的,我還錄制了視頻進行詳細講解,跟原始碼一起 ......

    uj5u.com 2023-07-09 07:46:41 more
  • Java版人臉跟蹤三部曲之三:編碼實戰

    ### 歡迎訪問我的GitHub > 這里分類和匯總了欣宸的全部原創(含配套原始碼):[https://github.com/zq2599/blog_demos](https://github.com/zq2599/blog_demos) ### 本篇概覽 - 作為《Java版人臉跟蹤三部曲》系列的終 ......

    uj5u.com 2023-07-09 07:46:29 more
  • P3378 【模板】二叉堆

    #[[洛谷]P3378 【模板】堆](https://www.luogu.com.cn/problem/P3378 "[【洛谷】P3378 【模板】堆]") ##方法一 手寫堆 - 最小堆插入 從新增的最后一個結點的父結點開始,用要插入元素向下過濾上層結點(相當于要插入的元素向上滲透) ```c++ ......

    uj5u.com 2023-07-09 07:46:20 more
  • 讓golang程式生成coredump檔案并進行除錯

    今天講講怎么讓golang程式生成coredump檔案,并且進行除錯的。 別看我寫了不少golang的博客,其實我平時寫c++的時間更多,所以也算和coredump是老相識了。`core dump`檔案實際上是行程在某個時間點時的記憶體映像,當時行程使用的記憶體是啥樣就會被原樣保存下來存在檔案系統的某個 ......

    uj5u.com 2023-07-09 07:46:12 more
  • C語言:資料結構之單鏈表(二)

    上一篇隨筆談了談單鏈表是什么東西,然后進行了初始化,這篇隨筆就開始對其進行操作了,首先是增,刪,改,查的增。 增,顧名思義就是要增加新的元素,單鏈表是鏈式的,那就要考慮怎么去加新元素,有三種,從頭部添加,從尾部添加,從中間添加。先說說從尾部添加,這個比較好理解,直接在尾部放一個結點然后連起來就好了。 ......

    uj5u.com 2023-07-09 07:45:59 more
  • python筆記:第四章使用字典

    ## 1.1 概述 > 說白了就是鍵值對的映射關系 > > 不會丟失資料本身關聯的結構,但不關注資料的順序 > > 是一種可變型別 ```py 格式:dic = {鍵:值, 鍵:值} ``` * 鍵的型別:字典的鍵可以是任何不可變的型別,如浮點數,字串,元組 ## 1.2 函式dict 可以從其他 ......

    uj5u.com 2023-07-09 07:45:17 more