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

MyBatisPlus中CRUD使用方法詳解

 更新時(shí)間:2023年01月31日 11:22:56   作者:Knight_AL  
通用CRUD封裝,BaseMapper(opens new window)接口,為Mybatis-Plus啟動時(shí)自動解析實(shí)體表關(guān)系映射轉(zhuǎn)換為Mybatis內(nèi)部對象注入容器

一、insert

1.插入操作

public class CRUDTests {
    @Autowired
    private UserMapper userMapper;
    @Test
    public void testInsert(){
        User user = new User();
        user.setName("Helen");
        user.setAge(18);
        user.setEmail("55317332@qq.com");
        int result = userMapper.insert(user);
        System.out.println(result); //影響的行數(shù)
        System.out.println(user); //id自動回填
    }
}

2.主鍵策略

要想主鍵自增需要配置如下主鍵策略

需要在創(chuàng)建數(shù)據(jù)表的時(shí)候設(shè)置主鍵自增

實(shí)體字段中配置 @TableId(type = IdType.AUTO)

@TableId(type = IdType.AUTO)
private Long id;

其它主鍵策略:分析 IdType 源碼可知

public enum IdType {
     /**
     * 數(shù)據(jù)庫ID自增
     */
    AUTO(0),
    /**
     * 該類型為未設(shè)置主鍵類型
     */
    NONE(1),
    /**
     * 用戶輸入ID
     * 該類型可以通過自己注冊自動填充插件進(jìn)行填充
     */    
    INPUT(2),
    /**
     * 全局唯一ID
     */    
    ASSIGN_ID(3),
    /**
     * 全局唯一ID (UUID)
     */
    ASSIGN_UUID(4),
    /** @deprecated */
    @Deprecated
    ID_WORKER(3),
    /** @deprecated */
    @Deprecated
    ID_WORKER_STR(3),
    /** @deprecated */
    @Deprecated
    UUID(4);
    private final int key;
    private IdType(int key) {
        this.key = key;
    }
    public int getKey() {
        return this.key;
    }
}

二、update

1.根據(jù)Id更新操作

注意:update時(shí)生成的sql自動是動態(tài)sql:UPDATE user SET age=? WHERE id=?

 @Test
    public void testUpdateById(){
        User user = new User();
        user.setId(1L);
        user.setAge(28);
        int result = userMapper.updateById(user);
        System.out.println(result);
    }

2.自動填充

項(xiàng)目中經(jīng)常會遇到一些數(shù)據(jù),每次都使用相同的方式填充,例如記錄的創(chuàng)建時(shí)間,更新時(shí)間等。

我們可以使用MyBatis Plus的自動填充功能,完成這些字段的賦值工作:

(1)數(shù)據(jù)庫表中添加自動填充字段

在User表中添加datetime類型的新的字段 create_time、update_time

(2)實(shí)體上添加注解(@TableField注解標(biāo)記對哪些字段,在什么時(shí)候進(jìn)行填充)

@Data
public class User {
    ......
    @TableField(fill = FieldFill.INSERT)
    private Date createTime;
    //@TableField(fill = FieldFill.UPDATE)
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Date updateTime;
}

(3)實(shí)現(xiàn)元對象處理器接口(在這個(gè)接口中指定對這些字段填充的數(shù)據(jù)時(shí)什么?)

注意:不要忘記添加 @Component 注解

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        this.setFieldValByName("createTime", new Date(), metaObject);
        this.setFieldValByName("updateTime", new Date(), metaObject);
    }
    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("updateTime", new Date(), metaObject);
    }
}

3.樂觀鎖

主要適用場景:當(dāng)要更新一條記錄的時(shí)候,希望這條記錄沒有被別人更新,也就是說實(shí)現(xiàn)線程安全的數(shù)據(jù)更新

樂觀鎖實(shí)現(xiàn)方式:

  • 取出記錄時(shí),獲取當(dāng)前version
  • 更新時(shí),帶上這個(gè)version
  • 執(zhí)行更新時(shí), set version = newVersion where version = oldVersion
  • 如果version不對,就更新失敗

(1)數(shù)據(jù)庫中添加version字段

ALTER TABLE `user` ADD COLUMN `version` INT

(2)實(shí)體類添加version字段

并添加 @Version 注解

@Version
@TableField(fill = FieldFill.INSERT)
private Integer version;

(3)元對象處理器接口添加version的insert默認(rèn)值

@Override
public void insertFill(MetaObject metaObject) {
    ......
    this.setFieldValByName("version", 1, metaObject);
}

特別說明:

支持的數(shù)據(jù)類型只有 int,Integer,long,Long,Date,Timestamp,LocalDateTime
整數(shù)類型下 newVersion = oldVersion + 1
newVersion 會回寫到 entity 中
僅支持 updateById(id) 與 update(entity, wrapper) 方法
在 update(entity, wrapper) 方法下, wrapper 不能復(fù)用!!!

(4)在 MybatisPlusConfig 中注冊 Bean

創(chuàng)建配置類

package com.atguigu.mybatisplus.config;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@EnableTransactionManagement  //該注解,目前沒有啥用[自我]
@Configuration
@MapperScan("com.atguigu.mybatis_plus.mapper") //該注解,目前沒有啥用[自我]
public class MybatisPlusConfig {
    /**
     * 樂觀鎖插件
     */
    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor() {
        return new OptimisticLockerInterceptor();
    }
}

(5)測試樂觀鎖可以修改成功

測試后分析打印的sql語句,將version的數(shù)值進(jìn)行了加1操作

/**
 * 測試 樂觀鎖插件
 */
@Test
public void testOptimisticLocker() {
    //查詢
    User user = userMapper.selectById(1L);
    //修改數(shù)據(jù)
    user.setName("Helen Yao");
    user.setEmail("helen@qq.com");
    //執(zhí)行更新
    userMapper.updateById(user);
}

(5)測試樂觀鎖修改失敗

/**
 * 測試樂觀鎖插件 失敗
 */
@Test
public void testOptimisticLockerFail() {
    //查詢
    User user = userMapper.selectById(1L);
    //修改數(shù)據(jù)
    user.setName("Helen Yao1");
    user.setEmail("helen@qq.com1");
    //模擬取出數(shù)據(jù)后,數(shù)據(jù)庫中version實(shí)際數(shù)據(jù)比取出的值大,即已被其它線程修改并更新了version
    user.setVersion(user.getVersion() - 1);
    //執(zhí)行更新
    userMapper.updateById(user);
}

三、select

1.根據(jù)id查詢記錄

@Test
public void testSelectById(){
    User user = userMapper.selectById(1L);
    System.out.println(user);
}

2.通過多個(gè)id批量查詢

完成了動態(tài)sql的foreach的功能

@Test
public void testSelectBatchIds(){
    List<User> users = userMapper.selectBatchIds(Arrays.asList(1, 2, 3));
    users.forEach(System.out::println);
}

3.簡單的條件查詢

通過map封裝查詢條件

@Test
public void testSelectByMap(){
    HashMap<String, Object> map = new HashMap<>();
    map.put("name", "Helen");
    map.put("age", 18);
    List<User> users = userMapper.selectByMap(map);
    users.forEach(System.out::println);
}

注意:map中的key對應(yīng)的是數(shù)據(jù)庫中的列名。例如數(shù)據(jù)庫user_id,實(shí)體類是userId,這時(shí)map的key需要填寫user_id

4.分頁

MyBatis Plus自帶分頁插件,只要簡單的配置即可實(shí)現(xiàn)分頁功能

(1)創(chuàng)建配置類

此時(shí)可以刪除主類中的 @MapperScan 掃描注解[也可以用主類上的@MapperScan注解:

/**
 * 分頁插件
 */
@Bean
public PaginationInterceptor paginationInterceptor() {
    return new PaginationInterceptor();
}

(2)測試selectPage分頁

測試:最終通過page對象獲取相關(guān)數(shù)據(jù)

@Test
public void testSelectPage() {
    Page<User> page = new Page<>(1,5);
    userMapper.selectPage(page, null);
    page.getRecords().forEach(System.out::println);
    System.out.println(page.getCurrent());
    System.out.println(page.getPages());
    System.out.println(page.getSize());
    System.out.println(page.getTotal());
    System.out.println(page.hasNext());
    System.out.println(page.hasPrevious());
}

控制臺sql語句打?。篠ELECT id,name,age,email,create_time,update_time FROM user LIMIT 0,5

(3)測試selectMapsPage分頁:結(jié)果集是Map

@Test
public void testSelectMapsPage() {
   //Page不需要泛型
   Page<Map<String, Object>> page = new Page<>(1, 5);
   Page<Map<String, Object>> pageParam = userMapper.selectMapsPage(page, null);
   List<Map<String, Object>> records = pageParam.getRecords();
   records.forEach(System.out::println);
   System.out.println(pageParam.getCurrent());
   System.out.println(pageParam.getPages());
   System.out.println(pageParam.getSize());
   System.out.println(pageParam.getTotal());
   System.out.println(pageParam.hasNext());
   System.out.println(pageParam.hasPrevious());
}

四、delete

1.根據(jù)id刪除記錄

@Test
public void testDeleteById(){
    int result = userMapper.deleteById(8L);
    System.out.println(result);
}

2.批量刪除

 @Test
    public void testDeleteBatchIds() {
        int result = userMapper.deleteBatchIds(Arrays.asList(8, 9, 10));
        System.out.println(result);
    }

3.簡單的條件查詢刪除

@Test
public void testDeleteByMap() {
    HashMap<String, Object> map = new HashMap<>();
    map.put("name", "Helen");
    map.put("age", 18);
    int result = userMapper.deleteByMap(map);
    System.out.println(result);
}

4.邏輯刪除

  • 物理刪除:真實(shí)刪除,將對應(yīng)數(shù)據(jù)從數(shù)據(jù)庫中刪除,之后查詢不到此條被刪除數(shù)據(jù)
  • 邏輯刪除:假刪除,將對應(yīng)數(shù)據(jù)中代表是否被刪除字段狀態(tài)修改為“被刪除狀態(tài)”,之后在數(shù)據(jù)庫中仍舊能看到此條數(shù)據(jù)記錄

(1)數(shù)據(jù)庫中添加 deleted字段

ALTER TABLE `user` ADD COLUMN `deleted` boolean

(2)實(shí)體類添加deleted 字段

并加上 @TableLogic 注解 和 @TableField(fill = FieldFill.INSERT) 注解

@TableLogic
@TableField(fill = FieldFill.INSERT)
private Integer deleted;

(3)元對象處理器接口添加deleted的insert默認(rèn)值

@Override
public void insertFill(MetaObject metaObject) {
    ......
    this.setFieldValByName("deleted", 0, metaObject);
}

(4)application.properties 加入配置

此為默認(rèn)值,如果你的默認(rèn)值和mp默認(rèn)的一樣,該配置可無

mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0

(5)測試邏輯刪除

  • 測試后發(fā)現(xiàn),數(shù)據(jù)并沒有被刪除,deleted字段的值由0變成了1
  • 測試后分析打印的sql語句,是一條update
  • 注意:被刪除數(shù)據(jù)的deleted 字段的值必須是 0,才能被選取出來執(zhí)行邏輯刪除的操作
/**
 * 測試 邏輯刪除
 */
@Test
public void testLogicDelete() {
    int result = userMapper.deleteById(1L);
    System.out.println(result);
}

(7)測試邏輯刪除后的查詢

MyBatis Plus中查詢操作也會自動添加邏輯刪除字段的判斷

/**
 * 測試 邏輯刪除后的查詢:
 * 不包括被邏輯刪除的記錄
 */
@Test
public void testLogicDeleteSelect() {
    User user = new User();
    List<User> users = userMapper.selectList(null);
    users.forEach(System.out::println);
}

測試后分析打印的sql語句,包含 WHERE deleted=0

SELECT id,name,age,email,create_time,update_time,deleted FROM user WHERE deleted=0

到此這篇關(guān)于MyBatisPlus中CRUD使用方法詳解的文章就介紹到這了,更多相關(guān)MyBatisPlus CRUD內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論

修武县| 金华市| 柳州市| 商都县| 海南省| 顺义区| 阜南县| 定陶县| 梧州市| 安仁县| 日土县| 区。| 楚雄市| 怀集县| 韶山市| 剑阁县| 蕉岭县| 天台县| 类乌齐县| 化州市| 江油市| 竹溪县| 贵溪市| 桃园市| 衢州市| 松桃| 汶川县| 辽中县| 灵石县| 碌曲县| 永福县| 两当县| 诸暨市| 舞钢市| 汉中市| 青岛市| 石渠县| 平罗县| 龙胜| 定襄县| 八宿县|