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

Mybatis-plus對(duì)單表操作的封裝實(shí)現(xiàn)

 更新時(shí)間:2024年12月19日 09:08:39   作者:five-five  
本文詳細(xì)介紹了MyBatis-Plus單表操作,包括自定義SQL、邏輯刪除、樂觀鎖、全局?jǐn)r截器和代碼生成器等,具有一定的參考價(jià)值,感興趣的可以了解一下

MyBatis-Plus是一個(gè)基于MyBatis的增強(qiáng)工具,它提供了豐富的CRUD操作和分頁查詢等功能,極大地簡化了開發(fā)人員的數(shù)據(jù)庫操作。本文將詳細(xì)介紹MyBatis-Plus官方已經(jīng)寫好的單表操作,并提供一些拓展內(nèi)容。

1. 引言

在進(jìn)行單表操作之前,我們需要定義一個(gè)實(shí)體類和對(duì)應(yīng)的Mapper接口。以下是一個(gè)簡單的實(shí)體類和Mapper接口示例:

@Data
@TableName("user")
public class User {
    @TableId(type = IdType.AUTO)
    private Long id;
    private String username;
    private String password;
    private Integer age;
}

@Mapper
public interface UserMapper extends BaseMapper<User> {
}

在實(shí)體類上使用@TableName注解指定對(duì)應(yīng)的數(shù)據(jù)庫表名,使用@TableId注解指定主鍵字段。在Mapper接口上使用@Mapper注解標(biāo)識(shí)該接口為Mapper接口,并繼承BaseMapper<User>,這樣就可以直接使用MyBatis-Plus提供的CRUD操作方法。

2. 單表操作

2.1 插入操作

插入操作可以使用insert方法,示例代碼如下:

User user = new User();
user.setUsername("Tom");
user.setPassword("123456");
user.setAge(18);

UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
int result = userMapper.insert(user);
if (result > 0) {
    System.out.println("插入成功");
}

2.2 查詢操作

查詢操作可以使用selectByIdselectList、selectPage等方法,示例代碼如下:

UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

// 根據(jù)ID查詢
User user = userMapper.selectById(1L);

// 根據(jù)條件查詢
LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(User::getUsername, "Tom");
List<User> userList = userMapper.selectList(queryWrapper);

// 分頁查詢
Page<User> page = new Page<>(1, 10);
LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.orderByDesc(User::getAge);
IPage<User> resultPage = userMapper.selectPage(page, queryWrapper);
List<User> userList = resultPage.getRecords();

2.3 更新操作

更新操作可以使用updateById方法,示例代碼如下:

User user = new User();
user.setId(1L);
user.setUsername("Jerry");
user.setPassword("654321");
user.setAge(20);

UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
int result = userMapper.updateById(user);
if (result > 0) {
    System.out.println("更新成功");
}

2.4 刪除操作

刪除操作可以使用deleteById、deleteBatchIdsdelete等方法,示例代碼如下:

UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

// 根據(jù)ID刪除
int result = userMapper.deleteById(1L);
if (result > 0) {
    System.out.println("刪除成功");
}

// 根據(jù)條件刪除
LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(User::getUsername, "Tom");
int result = userMapper.delete(queryWrapper);
if (result > 0) {
    System.out.println("刪除成功");
}

3. 拓展內(nèi)容

除了官方提供的基本CRUD操作外,MyBatis-Plus還提供了許多其他功能和拓展,以下是一些常用的拓展內(nèi)容:

3.1 自定義SQL

如果需要自定義SQL語句,可以使用BaseMapper提供的selectListselectById、insertupdateById、deleteById等方法的重載版本,傳入Wrapper對(duì)象和RowBounds對(duì)象進(jìn)行自定義查詢和分頁。

UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

// 自定義SQL查詢
LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.select(User::getId, User::getUsername)
            .orderByAsc(User::getAge);
List<User> userList = userMapper.selectList(queryWrapper, new RowBounds(0, 10));

// 自定義SQL插入
User user = new User();
user.setUsername("CustomUser");
user.setPassword("password");
user.setAge(25);
int result = userMapper.insert(user, new InsertWrapper<User>().setSql("INSERT INTO user(username, password, age) VALUES(#{username}, #{password}, #{age})"));

// 自定義SQL更新
User updateUser = new User();
updateUser.setId(1L);
updateUser.setUsername("UpdatedUser");
updateUser.setPassword("updatedPassword");
int result = userMapper.updateById(updateUser, new UpdateWrapper<User>

3.2 邏輯刪除

MyBatis-Plus提供了邏輯刪除功能,可以通過配置實(shí)體類和數(shù)據(jù)庫表字段實(shí)現(xiàn)。邏輯刪除是指在數(shù)據(jù)庫中將記錄的刪除標(biāo)志位設(shè)置為已刪除,而不是物理刪除記錄。這樣可以避免誤刪除數(shù)據(jù),同時(shí)也可以滿足一些特殊需求,例如數(shù)據(jù)恢復(fù)、數(shù)據(jù)審計(jì)等。

要使用邏輯刪除功能,需要在實(shí)體類上使用@TableLogic注解標(biāo)識(shí)刪除標(biāo)志位字段,并在Mapper接口上使用@Mapper注解的logicDelete屬性啟用邏輯刪除功能。示例代碼如下:

@Data
@TableName("user")
@TableLogic(value = "deleted", delval = "1")
public class User {
    @TableId(type = IdType.AUTO)
    private Long id;
    private String username;
    private String password;
    private Integer age;
    private Integer deleted;
}

@Mapper(logicDelete = true)
public interface UserMapper extends BaseMapper<User> {
}

在實(shí)體類上使用@TableLogic注解指定刪除標(biāo)志位字段和已刪除值,在Mapper接口上使用@Mapper注解的logicDelete屬性啟用邏輯刪除功能。這樣就可以使用deleteById、deleteBatchIdsdelete等方法進(jìn)行邏輯刪除操作。

3.3 樂觀鎖

MyBatis-Plus提供了樂觀鎖功能,可以通過配置實(shí)體類和數(shù)據(jù)庫表字段實(shí)現(xiàn)。樂觀鎖是一種并發(fā)控制策略,它假設(shè)多個(gè)事務(wù)并發(fā)執(zhí)行時(shí)不會(huì)發(fā)生沖突,每個(gè)事務(wù)在提交時(shí)都會(huì)驗(yàn)證其操作的數(shù)據(jù)是否已經(jīng)被其他事務(wù)修改過。如果發(fā)現(xiàn)數(shù)據(jù)已經(jīng)被修改,則當(dāng)前事務(wù)會(huì)回滾,避免了數(shù)據(jù)不一致的問題。

要使用樂觀鎖功能,需要在實(shí)體類上使用@Version注解標(biāo)識(shí)版本號(hào)字段,并在Mapper接口上使用@Mapper注解的optimisticLocker屬性啟用樂觀鎖功能。示例代碼如下:

@Data
@TableName("user")
@Version
public class User {
    @TableId(type = IdType.AUTO)
    private Long id;
    private String username;
    private String password;
    private Integer age;
    private Integer version;
}

@Mapper(optimisticLocker = true)
public interface UserMapper extends BaseMapper<User> {
}

在實(shí)體類上使用@Version注解標(biāo)識(shí)版本號(hào)字段,在Mapper接口上使用@Mapper注解的optimisticLocker屬性啟用樂觀鎖功能。這樣就可以使用updateById等方法進(jìn)行樂觀鎖更新操作。

3.4 全局?jǐn)r截器

MyBatis-Plus提供了全局?jǐn)r截器功能,可以通過實(shí)現(xiàn)Interceptor接口自定義攔截器,并在配置文件中注冊攔截器。全局?jǐn)r截器可以攔截所有的SQL語句,并在SQL執(zhí)行前后進(jìn)行一些自定義操作,例如記錄日志、權(quán)限校驗(yàn)等。

示例代碼如下:

@Component
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
public class MyInterceptor implements Interceptor {
    @Override
    public InterceptResult intercept(Invocation invocation) throws Throwable {
        // 在SQL執(zhí)行前進(jìn)行一些自定義操作
        System.out.println("Before SQL: " + invocation.getTarget());

        // 執(zhí)行SQL語句
        Object result = invocation.proceed();

        // 在SQL執(zhí)行后進(jìn)行一些自定義操作
        System.out.println("After SQL: " + invocation.getTarget());

        return InterceptResult.success(result);
    }
}

實(shí)現(xiàn)Interceptor接口,并使用@Intercepts注解標(biāo)識(shí)攔截的方法和參數(shù)類型。在intercept方法中進(jìn)行自定義操作,并使用invocation.proceed()執(zhí)行SQL語句。最后返回InterceptResult.success(result)表示攔截器執(zhí)行成功。

在配置文件中注冊攔截器,示例代碼如下:

<mybatis-plus>
    <configuration>
        <interceptors>
            <interceptor class="com.example.MyInterceptor"/>
        </interceptors>
    </configuration>
</mybatis-plus>

mybatis-plus標(biāo)簽中配置configuration標(biāo)簽,在configuration標(biāo)簽中配置interceptors標(biāo)簽,在interceptors標(biāo)簽中配置自定義攔截器類。

3.5 代碼生成器

MyBatis-Plus提供了代碼生成器功能,可以通過配置文件自動(dòng)生成實(shí)體類、Mapper接口、Service接口和Controller接口等代碼。代碼生成器可以大大提高開發(fā)效率,避免重復(fù)勞動(dòng)。

示例代碼如下:

<mybatis-plus-generator>
    <global-config>
        <output-dir>D:\code\mybatis-plus-generator\src\main\java</output-dir>
        <author>zhangsan</author>
        <open>false</open>
    </global-config>
    <data-source>
        <url>jdbc:mysql://localhost:3306/mybatis_plus</url>
        <username>root</username>
        <password>123456</password>
        <driver-class-name>com.mysql.jdbc.Driver</driver-class-name>
    </data-source>
    <package-info>
        <module-name>user</module-name>
        <parent>com.example</parent>
    </package-info>
    <strategy>
        <table-prefix>t_</table-prefix>
        <entity-lombok-model>true</entity-lombok-model>
        <rest-controller-style>true</rest-controller-style>
        <controller-mapping-hyphen-style>true</controller-mapping-hyphen-style>
        <include>t_user</include>
    </strategy>
</mybatis-plus-generator>

mybatis-plus-generator標(biāo)簽中配置代碼生成器的全局配置、數(shù)據(jù)源配置、包信息配置和策略配置。在global-config標(biāo)簽中配置輸出目錄、作者信息和是否自動(dòng)打開生成的文件夾。在data-source標(biāo)簽中配置數(shù)據(jù)庫連接信息。在package-info標(biāo)簽中配置包名信息。在strategy標(biāo)簽中配置表名前綴、實(shí)體類是否使用Lombok注解、Controller接口是否使用RESTful風(fēng)格和需要生成的表名。

運(yùn)行代碼生成器后,會(huì)自動(dòng)生成實(shí)體類、Mapper接口、Service接口和Controller接口等代碼。

4. 總結(jié)

MyBatis-Plus是一個(gè)非常強(qiáng)大的ORM框架,它提供了豐富的CRUD操作和分頁查詢等功能,同時(shí)也提供了許多其他功能和拓展,例如自定義SQL、邏輯刪除、樂觀鎖、全局?jǐn)r截器和代碼生成器等。使用MyBatis-Plus可以大大提高開發(fā)效率,同時(shí)也可以滿足一些特殊需求。

到此這篇關(guān)于Mybatis-plus對(duì)單表操作的封裝實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)Mybatisplus 單表操作內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Java線程編程中Thread類的基礎(chǔ)學(xué)習(xí)教程

    Java線程編程中Thread類的基礎(chǔ)學(xué)習(xí)教程

    這篇文章主要介紹了Java線程編程中Thread類的基礎(chǔ)學(xué)習(xí)教程,Thread類包含諸多操作線程的方法,非常重要,需要的朋友可以參考下
    2015-12-12
  • IDEA?設(shè)置?SpringBoot?logback?彩色日志的解決方法?附配置文件

    IDEA?設(shè)置?SpringBoot?logback?彩色日志的解決方法?附配置文件

    這篇文章主要介紹了IDEA?設(shè)置?SpringBoot?logback?彩色日志(附配置文件)的操作方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-12-12
  • Java實(shí)現(xiàn)文件批量重命名,移動(dòng)和刪除

    Java實(shí)現(xiàn)文件批量重命名,移動(dòng)和刪除

    這篇文章主要為大家介紹了如何利用Java語言實(shí)現(xiàn)批量重命名,批量移動(dòng)文件,批量刪除tmp文件等功能,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2022-08-08
  • Mybatis中特殊SQL的執(zhí)行

    Mybatis中特殊SQL的執(zhí)行

    這篇文章主要介紹了Mybatis中特殊SQL的執(zhí)行,介紹內(nèi)容包括模糊查詢、批量刪除、動(dòng)態(tài)設(shè)置表名、添加功能獲取自增的主鍵等相關(guān)資料,需要的小伙伴可以參考一下
    2022-04-04
  • 淺談resultMap的用法及關(guān)聯(lián)結(jié)果集映射

    淺談resultMap的用法及關(guān)聯(lián)結(jié)果集映射

    這篇文章主要介紹了resultMap的用法及關(guān)聯(lián)結(jié)果集映射操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-06-06
  • 關(guān)于Springboot如何獲取IOC容器

    關(guān)于Springboot如何獲取IOC容器

    大家好,我是孤焰。最近我在制作日志審計(jì)功能時(shí)發(fā)現(xiàn)不知道怎樣獲取到Springboot項(xiàng)目中的IOC容器,經(jīng)過摸索,最終解決了這個(gè)問題,現(xiàn)在把解決方式和大家分享一下
    2021-08-08
  • SpringBoot+MybatisPlus+代碼生成器整合示例

    SpringBoot+MybatisPlus+代碼生成器整合示例

    這篇文章主要介紹了SpringBoot+MybatisPlus+代碼生成器整合示例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-03-03
  • 用遞歸查找有序二維數(shù)組的方法詳解

    用遞歸查找有序二維數(shù)組的方法詳解

    本篇文章是對(duì)用遞歸查找有序二維數(shù)組的方法進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下
    2013-06-06
  • 教你怎么用Java通過關(guān)鍵字修改pdf

    教你怎么用Java通過關(guān)鍵字修改pdf

    此方法只適合通過關(guān)鍵字位置,在pdf上添加字符直接上代碼,代碼比較長,大部分自己的理解都在代碼注釋中了,需要的朋友可以參考下
    2021-05-05
  • 如何在java文件中設(shè)置文字顏色:setTextColor()

    如何在java文件中設(shè)置文字顏色:setTextColor()

    這篇文章主要介紹了如何在java文件中設(shè)置文字顏色:setTextColor(),文末補(bǔ)充介紹了在java代碼中設(shè)置字體顏色方法總結(jié),結(jié)合實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2023-09-09

最新評(píng)論