最近项目中使用到了 MyBatis-Plus。接下来快速搭建一个项目,快速入门 MyBatis-Plus。
官方文档非常详细:https://baomidou.com/pages/226c21/
来自官方介绍。
MyBatis-Plus (opens new window)(简称 MP)
是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
特性:
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
`id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`user_name` varchar(30) NOT NULL DEFAULT '' COMMENT '用户名',
`age` int NOT NULL DEFAULT 0 COMMENT '年龄',
`height` DOUBLE(10,2) NOT NULL DEFAULT 0.00 COMMENT '身高',
`email` varchar(50) NOT NULL DEFAULT '' COMMENT '邮箱',
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '修改时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户表';
--
DELETE FROM `t_user`;
INSERT INTO `t_user` (id, user_name, age, height, email) VALUES
(1, 'Jone', 18, 1.65, 'test1@baomidou.com'),
(2, 'Jack', 20, 1.60,'test2@baomidou.com'),
(3, 'Tom', 28, 1.75, 'test3@baomidou.com'),
(4, 'Sandy', 21, 1.72, 'test4@baomidou.com'),
(5, 'Billie', 24, 1.80, 'test5@baomidou.com');
创建 maven项目,引入依赖:
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-boot-starterartifactId>
<version>3.5.1version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.22version>
<scope>runtimescope>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-jdbcartifactId>
<version>2.5.8-SNAPSHOTversion>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druid-spring-boot-starterartifactId>
<version>1.2.3version>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>1.18.22version>
dependency>
server:
port: 18081
servlet:
context-path: /
spring:
application:
name: mybatis-plus-springboot
## 数据源配置
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver # com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/mybatis_db?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=GMT
username: root
password: 123456
logging:
level:
root: info
com.charge.learn.mybatis.plus: debug #打印SQL
到此,环境就搭建好了,可以使用 MyBatis-Plus。
@Data
@ToString
@TableName("t_user")
public class UserDO {
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@TableField("user_name")
private String userName;
private Integer age;
private Double height;
private String email;
@TableField(value = "create_time", fill = FieldFill.INSERT)
private Date createTime;
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
}
下面针对表创建 mapper,service等,进行使用。
说明:
BaseMapper(opens new window)接口
,为 Mybatis-Plus 启动时自动解析实体表关系映射转换为 Mybatis 内部对象注入容器所以,我们 POJO对应的Mapper接口只需要继承 BaseMapper接口,即可进行一些通用 CRUD的操作。对象 Wrapper 为 条件构造器后面在学习。
官方文档-Mapper CRUD 接口:https://baomidou.com/pages/49cc81/#mapper-crud-接口
public interface UserMapper extends BaseMapper<UserDO> {
}
就可以进行单元测试了。
@Autowired
private UserMapper userMapper;
@Test
public void testInsert() {
System.out.println(("----- insert method test ------"));
UserDO userDO = new UserDO();
userDO.setUserName("赵云");
userDO.setAge(20);
userDO.setHeight(1.88);
userDO.setEmail("zhaoyun@123.com");
int count = userMapper.insert(userDO);
System.out.println("count = " + count);
System.out.println("userDO = " + userDO);
}
注意:如果指定了 fill为后面三个时,必须显示设置值。否则为报错:Column 'create_time' cannot be null. 后面我们在使用字段自动填充。这里也可以不指定或者显示设置值。
@Test
public void testDeleteById() {
System.out.println(("----- deleteById method test ------"));
int count = userMapper.deleteById(1L);
System.out.println("count = " + count);
}
@Test
public void testUpdateById() {
System.out.println(("----- updateById method test ------"));
UserDO userDO = new UserDO();
userDO.setId(6L);
userDO.setUserName("赵子龙");
//userDO.setAge(21);
userDO.setHeight(1.908);
//userDO.setEmail("zhaoyun@123.com");
/**
* 因为 update_time,fill = INSERT_UPDATE,所以它必须设值,否则会报不能为null的错误
* @TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
*/
userDO.setUpdateTime(new Date()); /
int count = userMapper.updateById(userDO);
System.out.println("count = " + count);
System.out.println("userDO = " + userDO);
}
@Test
public void testSelectById() {
System.out.println(("----- selectById method test ------"));
UserDO userDO = userMapper.selectById(6L);
System.out.println("userDO = " + userDO);
}
@Test
public void testSelectList() {
System.out.println(("----- selectList method test ------"));
List<UserDO> userList = userMapper.selectList(null);
userList.forEach(System.out::println);
}
说明:
IService(opens new window)接口
,进一步封装 CRUD 采用 get 查询单行 remove 删除 list 查询集合 page 分页 前缀命名方式区分 Mapper 层避免混淆,官方文档-Service CRUD 接口:https://baomidou.com/pages/49cc81/#service-crud-接口
所以,我们 POJO对应的 server接口只需要继承 IService接口,即可进行一些通用 CRUD的操作。对象 Wrapper 为 条件构造器后面在学习。
public interface UserService extends IService<UserDO> {
}
注意:
ServiceImpl类
。更方便的简化我们的开发。@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements UserService {
}
ServiceImpl
就可以进行单元测试了。
@Autowired
private UserService userService;
@Test
public void testSave() {
System.out.println(("----- save method test ------"));
UserDO userDO = new UserDO();
userDO.setUserName("赵云save");
userDO.setAge(20);
userDO.setHeight(1.88);
userDO.setEmail("zhaoyun@123.com");
userDO.setCreateTime(new Date());
userDO.setUpdateTime(new Date());
boolean save = userService.save(userDO);
System.out.println("save = " + save);
System.out.println("userDO = " + userDO);
}
@Test
public void testSaveBatch() {
System.out.println(("----- saveBatch method test ------"));
List<UserDO> userDOList = new ArrayList<>();
for (int i = 0; i < 2; i++) {
UserDO userDO = new UserDO();
userDO.setUserName("赵云save" + i);
userDO.setAge(20);
//userDO.setHeight(1.88);
userDO.setEmail("zhaoyun@123.com");
userDO.setCreateTime(new Date());
userDO.setUpdateTime(new Date());
userDOList.add(userDO);
}
//boolean saveBatch = userService.saveBatch(userDOList);
int batchSize = 5;
boolean saveBatch = userService.saveBatch(userDOList, batchSize); //取userDOList的最小值
System.out.println("saveBatch = " + saveBatch);
}
@Test
public void testRemoveById() {
System.out.println(("----- removeById method test ------"));
boolean remove = userService.removeById(13L);
System.out.println("remove = " + remove);
}
@Test
public void testUpdateById() {
System.out.println(("----- updateById method test ------"));
UserDO userDO = new UserDO();
userDO.setId(11L);
userDO.setUserName("赵子龙");
//userDO.setAge(21);
userDO.setHeight(1.908);
//userDO.setEmail("zhaoyun@123.com");
userDO.setUpdateTime(new Date());
boolean update = userService.updateById(userDO);
System.out.println("update = " + update);
System.out.println("userDO = " + userDO);
}
@Test
public void testSaveOrUpdate() {
System.out.println(("----- save method test ------"));
UserDO userDO = new UserDO();
userDO.setId(110L); //id为null或者不存在时,新增,否则修改
userDO.setUserName("赵云saveOrUpdate");
userDO.setAge(20);
userDO.setHeight(1.88);
userDO.setEmail("zhaoyun@123.com");
userDO.setCreateTime(new Date());
userDO.setUpdateTime(new Date());
boolean saveOrUpdate = userService.saveOrUpdate(userDO);
System.out.println("saveOrUpdate = " + saveOrUpdate);
System.out.println("userDO = " + userDO);
}
@Test
public void testGetById() {
System.out.println(("----- getById method test ------"));
UserDO userDO = userService.getById(6L);
System.out.println("userDO = " + userDO);
}
@Test
public void testList() {
System.out.println(("----- list method test ------"));
List<UserDO> userList = userService.list(null);
userList.forEach(System.out::println);
}
– 求知若饥,虚心若愚。