一、介绍
mybatis—plus是一个mybatis的一个增强工具,它和mybatis相对独立,互不影响,可以极大程度的减少sql的书写量,简化开发。
缺点:只能作用于单表的维护,对于多表的联合操作,还需要我们自己手动书写代码。
二、使用流程
1、向pom文件中引入依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.1</version>
</dependency>
2、配置数据源
# ②修改配置文件
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/tttest?serverTimezone=Asia/Shanghai
spring.datasource.password=
spring.datasource.username=root
logging.level.com.lbk.test.mapper=debug
URL,USERNAME,PASSWORD因人而异,请换成自己的数据库信息。
3、书写对应表的实体类(pojo)
//当封装的实体的名字的名字和数据库里的表名不一致的时候使用此注解指定
@TableName(value = "tab_account")
public class TabAccount {
@TableId(type = IdType.AUTO)
/* @TableId(type = IdType.ASSIGN_ID)*/
//在新增的时候,要么使用雪花生成主键ID(上一),要么使用主键自增(上二)
private Integer account_id;
private Integer empId;
private String username;
private String password;
4、书写Mapper
@Component
public interface SelectMapper extends BaseMapper<TabAccount> {
}
并且在启动类中加入@MapperScan(basePackages = {"xx.xx.xx.mapper"})
5、单元测试,对表进行 CRUD 操作、
@SpringBootTest
class DemoApplicationTests {
@Resource
private SelectMapper mapper;
@Test
void contextLoads() {
TabAccount tabAccount = mapper.selectById(1);
System.out.println(tabAccount);
}
}
我们可以按住Ctrl+鼠标左键点击selectById,进入到BaseMapper中,查看所有的方法以及递增实现原理。
Mybatis-plus用起来真滴舒服,雀食蟀。搞起来搞起来。