偷偷摘套内射激情视频,久久精品99国产国产精,中文字幕无线乱码人妻,中文在线中文a,性爽19p

SpringBoot 整合 Mybatis 實(shí)現(xiàn)數(shù)據(jù)表增刪改查,保姆級(jí)教程!

開(kāi)發(fā) 前端
本文主要圍繞利用 Mybatis 框架來(lái)實(shí)現(xiàn)對(duì)數(shù)據(jù)庫(kù)表的快速訪問(wèn)操作,與 Spring Boot JPA 相比,Mybatis 在使用上更加靈活,對(duì)數(shù)據(jù)表的操作就像在本地?cái)?shù)據(jù)庫(kù)寫(xiě) SQL 一樣方便,對(duì)于業(yè)務(wù)復(fù)雜的查詢(xún)場(chǎng)景,它比 Spring Boot JPA 要靈活很多。

01、背景介紹

在上一篇文章中,我們介紹了利用 Spring Boot JPA 來(lái)實(shí)現(xiàn)對(duì)數(shù)據(jù)庫(kù)的訪問(wèn)操作,雖然它在國(guó)外廣泛流行,但是在國(guó)內(nèi)流行程度遠(yuǎn)不如 MyBatis。

原因在于,在 ORM 框架中其實(shí)還有另一個(gè)翹楚,那就是剛剛說(shuō)到的 MyBatis,它的實(shí)現(xiàn)方式與 Spring Boot JPA 完全不同,MyBatis 框架不會(huì)幫助用戶(hù)動(dòng)態(tài)生成 SQL 語(yǔ)句,它把 SQL 的編寫(xiě)工作完全交給了用戶(hù),開(kāi)發(fā)者可以像在本地?cái)?shù)據(jù)庫(kù)中寫(xiě) SQL 語(yǔ)句一樣快速的完成對(duì)數(shù)據(jù)庫(kù)表的操作,非常易于新人上手,唯一的缺點(diǎn)就是配置工作量很大,好在有代碼生成器,可以幫助開(kāi)發(fā)者減輕不少的開(kāi)發(fā)工作量。

ORM 框架發(fā)展至今,只剩下兩家了,一個(gè)是以Hibernate為代表,開(kāi)發(fā)者可以不用寫(xiě)一句 SQL 就可以輕松完成對(duì)數(shù)據(jù)庫(kù)的訪問(wèn)操作;另一個(gè)是以MyBatis為代表,開(kāi)發(fā)者可以根據(jù)自己的業(yè)務(wù)需求靈活的編寫(xiě)動(dòng)態(tài) SQL 完成對(duì)數(shù)據(jù)庫(kù)的訪問(wèn)操作。

總的來(lái)說(shuō),兩者各有特點(diǎn),如果當(dāng)前業(yè)務(wù)所有的業(yè)務(wù)操作都是單表并且沒(méi)有很復(fù)雜的查詢(xún)要求,那么采用 Spring Boot JPA 來(lái)開(kāi)發(fā),效率會(huì)更高;如果業(yè)務(wù)很復(fù)雜,各表之間經(jīng)常需要連表查詢(xún),那么采用MyBatis來(lái)開(kāi)發(fā)會(huì)是一個(gè)非常好的選擇。在企業(yè)級(jí)系統(tǒng)開(kāi)發(fā)中,因?yàn)闃I(yè)務(wù)比較復(fù)雜,國(guó)內(nèi)采用MyBatis來(lái)開(kāi)發(fā)的項(xiàng)目相對(duì)比較多些。

今天這篇文章我們就具體來(lái)說(shuō)說(shuō)如何在 Spring Boot 中整合 MyBatis 完成數(shù)據(jù)庫(kù)表的增刪改查操作。

02、應(yīng)用實(shí)踐

2.1、工程配置

首先,在pom.xml文件中引入mybatis-spring-boot-starter依賴(lài),具體如下:

<!--spring boot mybatis支持-->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.0.0</version>
</dependency>
<!--mysql 驅(qū)動(dòng)-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

關(guān)于mybatis-spring-boot-starter與Spring Boot的版本對(duì)應(yīng)關(guān)系,可以參考如下:

  • 1.3.x版本:適用于 MyBatis 3.4+、Java 6+、Spring Boot 1.5
  • 2.0.x版本:適用于 MyBatis 3.5+、Java 8+、Spring Boot 2.0/2.1
  • 2.1.x版本:適用于 MyBatis 3.5+、Java 8+、Spring Boot 2.1+

本項(xiàng)目采用的是Spring Boot 2.1.0構(gòu)建,因此選擇2.0.0版本。

然后,在application.properties文件中添加數(shù)據(jù)源信息和相關(guān)的MyBatis配置參數(shù),內(nèi)容如下:

# 數(shù)據(jù)源配置
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

# 打印SQL語(yǔ)句
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

MyBatis支持兩種開(kāi)發(fā)模式。

  • 第一種:基于注解的配置實(shí)現(xiàn)
  • 第二種:基于XML的配置實(shí)現(xiàn)

下面我們一起來(lái)這兩種具體的應(yīng)用方式。

2.2、基于注解的配置實(shí)現(xiàn)

基于注解的配置實(shí)現(xiàn),簡(jiǎn)單的說(shuō)就是采用注解來(lái)開(kāi)發(fā),具體實(shí)現(xiàn)如下。

2.2.1、創(chuàng)建數(shù)據(jù)庫(kù)表

首先,mybatis框架不會(huì)幫助我們根據(jù)實(shí)體類(lèi)自動(dòng)生成目標(biāo)數(shù)據(jù)庫(kù)表,因此我們需要事先設(shè)計(jì)好數(shù)據(jù)庫(kù)表結(jié)構(gòu),在此我們以角色表tb_role為例,具體創(chuàng)建命令如下。

CREATE TABLE `tb_role` (
  `id` int(11) unsigned NOT NULL COMMENT '主鍵ID',
  `role_name` varchar(50) DEFAULT NULL COMMENT '角色名稱(chēng)',
  `create_time` datetime DEFAULT NULL COMMENT '創(chuàng)建時(shí)間',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

2.2.2、編寫(xiě)對(duì)應(yīng)的實(shí)體類(lèi)

package com.example.springboot.entity;

public class Role {

    /**
     * 主鍵ID
     */
    private Integer id;

    /**
     * 角色名稱(chēng)
     */
    private String roleName;

    /**
     * 創(chuàng)建時(shí)間
     */
    private Date createTime;

    // set、get方法等...
}

2.2.3、編寫(xiě)對(duì)應(yīng)的 Mapper 接口

package com.example.springboot.mapper;

public interface RoleMapper {

    @Select("select * from tb_role")
    @Results({
            @Result(property = "id",  column = "id"),
            @Result(property = "roleName",  column = "role_name"),
            @Result(property = "createTime", column = "create_time")
    })
    List<Role> findAll();

    @Select("select * from tb_role where id =#{id}")
    @Results({
            @Result(property = "id",  column = "id"),
            @Result(property = "roleName",  column = "role_name"),
            @Result(property = "createTime", column = "create_time")
    })
    Role findById(@Param("id") Integer id);

    @Insert("insert into tb_role(id, role_name, create_time) VALUES(#{id}, #{roleName}, #{createTime})")
    int insert(Role role);

    @Update("update tb_role set role_name=#{roleName} WHERE id=#{id}")
    int update(Role role);

    @Delete("delete from tb_role where id =#{id}")
    int delete(@Param("id") Integer id);
}

2.2.4、添加 Mapper 接口掃描路徑

默認(rèn)創(chuàng)建的 Mapper 接口無(wú)法被自動(dòng)加載到 Spring IOC 容器中,因此需要在Application啟動(dòng)類(lèi)上,添加 Mapper 接口的包掃描路徑,可以通過(guò)@MapperScan注解來(lái)完成注入,具體如下。

@MapperScan("com.example.springboot.mapper")
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

2.2.5、單元測(cè)試

最后,我們編寫(xiě)單元測(cè)試來(lái)驗(yàn)證一下內(nèi)容的正確性,代碼如下:

@RunWith(SpringRunner.class)
@SpringBootTest
@Transactional
public class RoleMapperJunit {

    @Autowired
    private RoleMapper roleMapper;

    @Test
    public void test(){
        // 新增數(shù)據(jù)
        roleMapper.insert(new Role(1, "開(kāi)發(fā)工程師", new Date()));
        roleMapper.insert(new Role(2, "測(cè)試工程師", new Date()));
        roleMapper.insert(new Role(3, "項(xiàng)目經(jīng)理", new Date()));

        // 查詢(xún)數(shù)據(jù)
        List<Role> roleList = roleMapper.findAll();
        System.out.println("第一次查詢(xún)?nèi)繑?shù)據(jù)結(jié)果:" + roleList.toString());

        System.out.println("----------------------");

        // 修改單條數(shù)據(jù)
        roleMapper.update(new Role(1, "技術(shù)經(jīng)理"));

        // 單條查詢(xún)
        Role role = roleMapper.findById(1);
        System.out.println("查詢(xún)[id=1]結(jié)果:" + role.toString());

        System.out.println("----------------------");

        // 刪除單條數(shù)據(jù)
        roleMapper.delete(1);

        // 查詢(xún)數(shù)據(jù)
        List<Role> roleList1 = roleMapper.findAll();
        System.out.println("第二次查詢(xún)?nèi)繑?shù)據(jù)結(jié)果:" + roleList1.toString());
    }
}

運(yùn)行單元測(cè)試,輸出結(jié)果如下!

第一次查詢(xún)?nèi)繑?shù)據(jù)結(jié)果:[Role{id=1, roleName='開(kāi)發(fā)工程師', createTime=Sun Apr 28 11:44:52 CST 2024}, Role{id=2, roleName='測(cè)試工程師', createTime=Sun Apr 28 11:44:52 CST 2024}, Role{id=3, roleName='項(xiàng)目經(jīng)理', createTime=Sun Apr 28 11:44:52 CST 2024}]
----------------------
查詢(xún)[id=1]結(jié)果:Role{id=1, roleName='技術(shù)經(jīng)理', createTime=Sun Apr 28 11:44:52 CST 2024}
----------------------
第二次查詢(xún)?nèi)繑?shù)據(jù)結(jié)果:[Role{id=2, roleName='測(cè)試工程師', createTime=Sun Apr 28 11:44:52 CST 2024}, Role{id=3, roleName='項(xiàng)目經(jīng)理', createTime=Sun Apr 28 11:44:52 CST 2024}]

至此,基于注解模式的實(shí)現(xiàn)方式已經(jīng)介紹完畢了。

如果有一定開(kāi)發(fā)經(jīng)歷的同學(xué)可能會(huì)感覺(jué)到,基于注解方式的開(kāi)發(fā)模式雖然簡(jiǎn)單,但是弊端也很大,假如查詢(xún)的時(shí)候,需要連接的表很多,字段也多,代碼可讀性就變得很差,因此大多數(shù)情況下,開(kāi)發(fā)者會(huì)更傾向于選擇基于 XML 的配置實(shí)現(xiàn)方式開(kāi)發(fā),原因是它的可讀性更高。

2.3、基于XML的配置實(shí)現(xiàn)

基于 XML 的配置實(shí)現(xiàn),是一種最常用的開(kāi)發(fā)模式,具體實(shí)現(xiàn)如下。

2.3.1、創(chuàng)建數(shù)據(jù)庫(kù)表

與上面類(lèi)似,我們創(chuàng)建一張新表tb_menu來(lái)介紹,具體創(chuàng)建命令如下。

CREATE TABLE `tb_menu` (
  `id` int(11) unsigned NOT NULL COMMENT '主鍵ID',
  `menu_name` varchar(50) DEFAULT NULL COMMENT '菜單名稱(chēng)',
  `create_time` datetime DEFAULT NULL COMMENT '創(chuàng)建時(shí)間',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

2.3.2、編寫(xiě)對(duì)應(yīng)的實(shí)體類(lèi)

package com.example.springboot.entity;

public class Menu {

    /**
     * 主鍵ID
     */
    private Integer id;

    /**
     * 菜單名稱(chēng)
     */
    private String menuName;

    /**
     * 創(chuàng)建時(shí)間
     */
    private Date createTime;

    // set、get方法等...
}

2.3.3、編寫(xiě)對(duì)應(yīng)的 Mapper 接口

與上面基于注解的開(kāi)發(fā)模式類(lèi)似,只是少了注解配置。

package com.example.springboot.mapper;

public interface MenuMapper {

    List<Menu> findAll();

    Menu findById(@Param("id") Integer id);

    int insert(Menu role);

    int update(Menu role);

    int delete(@Param("id") Integer id);
}

2.3.4、創(chuàng)建 XML 映射文件

在src/main/resources/mybatis/mapper目錄下創(chuàng)建MenuMapper.xml文件,并與 Mapper 接口建立映射關(guān)系,內(nèi)容如下:

<?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.springboot.mapper.MenuMapper">

    <!--BaseResultMap-->
    <resultMap id="BaseResultMap" type="com.example.springboot.entity.Menu" >
        <id column="id" property="id" jdbcType="INTEGER" />
        <result column="menu_name" property="menuName" jdbcType="VARCHAR" />
        <result column="create_time" property="createTime" jdbcType="TIMESTAMP"/>
    </resultMap>

    <!--Base_Column_List-->
    <sql id="Base_Column_List">
        id
        ,menu_name
        ,create_time
    </sql>

    <select id="findAll" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List"/>
        from tb_menu
        order by id
    </select>

    <select id="findById" resultMap="BaseResultMap" parameterType="java.lang.Integer">
        select
        <include refid="Base_Column_List"/>
        from tb_menu
        where id = #{id,jdbcType=INTEGER}
    </select>

    <insert id="insert" parameterType="com.example.springboot.entity.Menu">
        insert into tb_menu(id, menu_name, create_time)
        values(#{id}, #{menuName}, #{createTime})
    </insert>

    <update id="update" parameterType="com.example.springboot.entity.Menu">
        update tb_menu
        set menu_name = #{menuName,jdbcType=VARCHAR}
        where id = #{id,jdbcType=INTEGER}
    </update>

    <delete id="delete" parameterType="java.lang.Integer">
        delete from tb_menu
        where id = #{id,jdbcType=INTEGER}
    </delete>

</mapper>

2.3.5、創(chuàng)建 Mybatis 全局配置文件

在src/main/resources/mybatis目錄下創(chuàng)建mybatis-config.xml文件,可以全局配置 mybatis 相關(guān)屬性信息,示例如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <settings>
        <!-- 指定MyBatis所用日志的具體實(shí)現(xiàn),STDOUT_LOGGING:表示打印到控制臺(tái)-->
        <setting name="logImpl" value="STDOUT_LOGGING" />
    </settings>

    <typeAliases>
        <!--配置類(lèi)型別名可為Java類(lèi)型設(shè)置一個(gè)縮寫(xiě)名字,以便于在xml中通過(guò)簡(jiǎn)寫(xiě)來(lái)代替全限定類(lèi)名-->
        <typeAlias alias="Integer" type="java.lang.Integer" />
        <typeAlias alias="Long" type="java.lang.Long" />
        <typeAlias alias="HashMap" type="java.util.HashMap" />
        <typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap" />
        <typeAlias alias="ArrayList" type="java.util.ArrayList" />
        <typeAlias alias="LinkedList" type="java.util.LinkedList" />
    </typeAliases>

</configuration>

更多的配置屬性,可以參考這篇文章。

2.3.6、添加 Mapper 接口掃描路徑

同上,需要在Application啟動(dòng)類(lèi)上添加 Mapper 接口的包掃描路徑,如果已添加,可以忽略。

@MapperScan("com.example.springboot.mapper")
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

2.3.7、配置 XML 文件掃描路徑

與基于注解的開(kāi)發(fā)模式稍有不同,我們還需要在application.properties文件中配置 Mybatis 相關(guān)的 XML 文件掃描目錄,否則啟動(dòng)報(bào)錯(cuò),內(nèi)容如下:

# 配置mybatis全局配置文件掃描
mybatis.config-location=classpath:mybatis/mybatis-config.xml
# 配置mybatis的xml配置文件掃描目錄
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
# 打印SQL語(yǔ)句,需要注射掉這個(gè)mybatis全局屬性配置,否則啟動(dòng)報(bào)錯(cuò)
#mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

2.3.8、單元測(cè)試

最后,我們編寫(xiě)單元測(cè)試來(lái)驗(yàn)證一下內(nèi)容的正確性,代碼如下:

public class MenuMapperJunit {

    @Autowired
    private MenuMapper menuMapper;

    @Test
    public void test(){
        // 新增數(shù)據(jù)
        menuMapper.insert(new Menu(1, "用戶(hù)菜單", new Date()));
        menuMapper.insert(new Menu(2, "角色菜單", new Date()));
        menuMapper.insert(new Menu(3, "系統(tǒng)菜單", new Date()));

        // 查詢(xún)數(shù)據(jù)
        List<Menu> menuList = menuMapper.findAll();
        System.out.println("第一次查詢(xún)?nèi)繑?shù)據(jù)結(jié)果:" + menuList.toString());

        System.out.println("----------------------");

        // 修改單條數(shù)據(jù)
        menuMapper.update(new Menu(1, "項(xiàng)目菜單"));

        // 單條查詢(xún)
        Menu menu = menuMapper.findById(1);
        System.out.println("查詢(xún)[id=1]結(jié)果:" + menu.toString());

        System.out.println("----------------------");

        // 刪除單條數(shù)據(jù)
        menuMapper.delete(1);

        // 查詢(xún)數(shù)據(jù)
        List<Menu> menuList1 = menuMapper.findAll();
        System.out.println("第二次查詢(xún)?nèi)繑?shù)據(jù)結(jié)果:" + menuList1.toString());
    }
}

運(yùn)行單元測(cè)試,輸出結(jié)果如下!

第一次查詢(xún)?nèi)繑?shù)據(jù)結(jié)果:[Menu{id=1, menuName='用戶(hù)菜單', createTime=Sun Apr 28 14:24:49 CST 2024}, Menu{id=2, menuName='角色菜單', createTime=Sun Apr 28 14:24:49 CST 2024}, Menu{id=3, menuName='系統(tǒng)菜單', createTime=Sun Apr 28 14:24:50 CST 2024}]
----------------------
查詢(xún)[id=1]結(jié)果:Menu{id=1, menuName='項(xiàng)目菜單', createTime=Sun Apr 28 14:24:49 CST 2024}
----------------------
第二次查詢(xún)?nèi)繑?shù)據(jù)結(jié)果:[Menu{id=2, menuName='角色菜單', createTime=Sun Apr 28 14:24:49 CST 2024}, Menu{id=3, menuName='系統(tǒng)菜單', createTime=Sun Apr 28 14:24:50 CST 2024}]

至此,基于 XML 模式的實(shí)現(xiàn)方式已經(jīng)介紹完畢了。

實(shí)際開(kāi)發(fā)過(guò)程中,如果不需要自定義全局配置 Mybatis 數(shù)據(jù),也可以省掉創(chuàng)建 Mybatis 全局配置文件這一步。

03、小結(jié)

本文主要圍繞利用 Mybatis 框架來(lái)實(shí)現(xiàn)對(duì)數(shù)據(jù)庫(kù)表的快速訪問(wèn)操作,與 Spring Boot JPA 相比,Mybatis 在使用上更加靈活,對(duì)數(shù)據(jù)表的操作就像在本地?cái)?shù)據(jù)庫(kù)寫(xiě) SQL 一樣方便,對(duì)于業(yè)務(wù)復(fù)雜的查詢(xún)場(chǎng)景,它比 Spring Boot JPA 要靈活很多。而且可維護(hù)性更高。

如果是企業(yè)級(jí)的 web 項(xiàng)目,推薦采用 Mybatis 框架作為持久層。

04、參考

  1. https://mybatis.net.cn/
責(zé)任編輯:武曉燕 來(lái)源: 潘志的研發(fā)筆記
相關(guān)推薦

2024-08-29 08:58:30

JPA編寫(xiě)數(shù)據(jù)操

2021-10-20 09:04:21

Spring Beanscope數(shù)據(jù)庫(kù)

2020-05-28 16:50:59

源碼分析 MybatisJava

2012-04-19 10:06:16

ibmdw

2019-11-07 15:39:36

數(shù)據(jù)庫(kù)MySQL文章

2021-07-05 09:24:06

MySQL SQL 語(yǔ)句數(shù)據(jù)庫(kù)

2023-02-27 07:37:56

Curl操作SQL

2024-11-18 00:22:34

2012-04-12 09:23:15

達(dá)夢(mèng)數(shù)據(jù)庫(kù)

2009-11-13 15:54:26

ADO.NET數(shù)據(jù)庫(kù)操

2023-06-07 08:08:37

MybatisSpringBoot

2023-06-08 08:13:43

2024-07-26 10:50:51

SpringScrew數(shù)據(jù)庫(kù)

2022-12-01 11:41:24

2022-12-12 11:47:34

WindowsPySpark服務(wù)器

2020-10-29 08:39:45

JSONJava對(duì)象

2025-04-11 10:13:00

數(shù)據(jù)庫(kù)APIFastAPI

2022-04-28 07:31:41

Springkafka數(shù)據(jù)量

2021-05-19 09:53:16

SpringbootMyBatisMySQL

2023-07-06 09:01:33

點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)