MyBatis-Plus (简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。官网:https://mp.baomidou.com/
- 创建user表,用于接下来MyBatisPlus对表进行CRUD操作
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`name` varchar(30) DEFAULT NULL COMMENT '姓名',
`age` int(11) DEFAULT NULL COMMENT '年龄',
`email` varchar(50) DEFAULT NULL COMMENT '邮箱',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
`update_time` datetime DEFAULT NULL COMMENT '修改时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
/*Data for the table `user` */
insert into `user`
(`id`,`name`,`age`,`email`,`create_time`,`update_time`)
values
(1,'Jone',18,'[email protected]',NULL,NULL),
(2,'Jack',20,'[email protected]',NULL,NULL),
(3,'Tom',28,'[email protected]',NULL,NULL),
(4,'Sandy',21,'[email protected]',NULL,NULL),
(5,'Billie',24,'[email protected]',NULL,NULL);
- 创建springboot项目并导入相关maven依赖
<dependencies>
<!--数据库-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.14</version>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!--Swagger-UI API文档生产工具-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.1</version>
</dependency>
<!--国产的开源框架,并没有接入到 Spring 官方孵化器中-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
- 在application.yml文件中配置数据库进行连接数据库
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
username: root
password: root
url: jdbc:mysql://localhost:3306/mybatis_plus?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&llowMultiQueries=true
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
- 创建实体类和Mapper接口,并且在启动类上添加上注解
@MapperScan("com.sakura.mybatis_plus.mapper")
@Data
public class User {
private long id;
private String name;
private Integer age;
private String email;
//该注解用于在进行创建和修改时自动填充时间
//@TableField(fill = FieldFill.INSERT)
private Date createTime;
//@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
}
@Repository
public interface UserMapper extends BaseMapper<User> {
}
@MapperScan("com.sakura.mybatis_plus.mapper")
@SpringBootApplication
public class MybatisPlusApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisPlusApplication.class, args);
}
}
- 可以在测试类中对测试是否连接上数据库并且是否可以使用MybatisPlus进行CRUD操作
@SpringBootTest
class UserMapperTest {
@Autowired
private UserMapper userMapper;
@Test
public void query(){
userMapper.selectList(null).forEach(System.out::println);
}
@Test
public void insert(){
User user = new User();
user.setName("Sakura");
user.setAge(21);
user.setEmail("[email protected]");
int insert = userMapper.insert(user);
System.out.println(insert>0?"插入成功":"插入失败");
}
@Test
public void update(){
User user = new User();
user.setId(1L);
user.setAge(58);
int i = userMapper.updateById(user);
System.out.println(i>0?"修改成功":"修改失败");
}
@Test
public void delete(){
Map<String,Object> condition = new HashMap<>();
condition.put("name","Sakura");
int i = userMapper.deleteByMap(condition);
System.out.println(i>0?"删除成功":"删除失败");
}
}
这里只是简单的介绍了下具体整合的操作,其实MyBatisPlus有很多有用的功能,这里就以自动填充为例
- 在实体类属性对应位置添加上注解(这里以创建和修改时间为例,每次该字段的内容不需要由我们手动添加而交给mybatisplus在进行)
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
- 编写处理器在处理这个注解
@Slf4j
@Component //添加该注解表示将该组件加入到IOC容器中
public class MyBatisPlusHandler implements MetaObjectHandler {
//插入时的填充策略
@Override
public void insertFill(MetaObject metaObject) {
log.info("start insert fill...");
//MyBatisPlus在进行插入时会自动将创建时间和修改时间填充进去
this.setFieldValByName("createTime",new Date(),metaObject);
this.setFieldValByName("updateTime",new Date(),metaObject);
}
//修改时的填充策略
@Override
public void updateFill(MetaObject metaObject) {
log.info("start update fill...");
//MyBatisPlus在进行修改操作时只对updateTime进行填充
this.setFieldValByName("updateTime",new Date(),metaObject);
}
}
运行结果:
执行下面这代码
@Test
public void insert(){
User user = new User();
user.setName("Sakura");
user.setAge(21);
user.setEmail("[email protected]");
int insert = userMapper.insert(user);
System.out.println(insert>0?"插入成功":"插入失败");
}
在mysql中即可发现相关时间字段都自动填充了
同样在进行修改操作时也同样会对UpdateTime进行填充修改