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;
}
}