mybatis的使用及源码分析(十三) 测试mybatis-plus使用AR模式

本文介绍了如何使用Mybatis-Plus的ActiveRecord (AR) 模式进行数据库操作,包括创建表结构、定义实体类继承Model、编写Mapper接口,并通过Controller实现增删改查(CRUD)操作,展示了从模型到实际应用的完整流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

AR即为ActiveRecord,是一种领域模型模式,一个模型类对应一个表。通过实体类对象直接进行表的CRUD操作。

1、导入测试的一个表

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for test_mp_ar
-- ----------------------------
DROP TABLE IF EXISTS `test_mp_ar`;
CREATE TABLE `test_mp_ar`  (
  `id` int(0) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;

SET FOREIGN_KEY_CHECKS = 1;

2、定义实体继承Model

/**
 * 测试mybatis-plus AR模式
 *
 * @author zhuquanwen
 * @vesion 1.0
 * @date 2021/4/7 20:54
 * @since jdk1.8
 */
@Data
public class TestMpAr extends Model<TestMpAr> {
    @TableId(type = IdType.AUTO)
    private Integer id;
    private String name;
}

3、定义Mapper
必须定义Mapper,否则不能使用AR模式

/**
 *
 * @author zhuquanwen
 * @vesion 1.0
 * @date 2021/4/7 20:56
 * @since jdk1.8
 */
@Repository
@Mapper
public interface TestMpArMapper extends BaseMapper<TestMpAr> {
}

4、测试CURD

/**
 *
 * @author zhuquanwen
 * @vesion 1.0
 * @date 2021/4/7 20:57
 * @since jdk1.8
 */
@RequestMapping("/test/mp/ar")
@RestController
public class TestMapArController extends BaseController {

    @PostMapping("/insert")
    public ResponseEntity insert() {
        ResponseEntity response = getResponse();
        TestMpAr testMpAr = new TestMpAr();
        testMpAr.setName("test1");
        testMpAr.insert();
        return response;
    }

    @PutMapping("/update")
    public ResponseEntity update() {
        ResponseEntity response = getResponse();
        TestMpAr testMpAr = new TestMpAr();
        testMpAr = testMpAr.selectById(1);
        testMpAr.setName("test111");
        testMpAr.updateById();
        return response;
    }

    @GetMapping("/search")
    public ResponseEntity search() {
        ResponseEntity response = getResponse();
        TestMpAr testMpAr = new TestMpAr();
        QueryWrapper<TestMpAr> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("name", "test");
        List<TestMpAr> testMpArs = testMpAr.selectList(queryWrapper);
        response.setValue(testMpArs);
        return response;
    }

    @DeleteMapping("/delete")
    public ResponseEntity delete() {
        ResponseEntity response = getResponse();
        TestMpAr testMpAr = new TestMpAr();
        testMpAr.setId(1);
        testMpAr.deleteById();
        return response;
    }

}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值