文章目录
- Mybatis-Plus 框架基础
- 引入 maven 依赖
- 定义实体类,并标注注解
- 定义 Mapper 接口,要求继承自特定父接口
- 使用 @MapperScan 注解,扫描 mapper 接口所在位置
- 验证
Mybatis-Plus 框架基础
MyBatis-Plus 是 MyBatis 的一种增强框架,目的就是为了简化开发,提高开发效率。数据库支持:任何能使用 MyBatis 进行 crud ,并且支持标准 SQL 的数据库。
mybatis-plus:configuration:log-impl: org.apache.ibatis.logging.stdout.StdOutImpl# 这里配置了 MyBatis-Plus 的日志实现, 表示日志将输出到标准输出流(stdout)。# 这样配置可以方便在控制台中查看 MyBatis-Plus 的日志输出。global-config:banner: false# 表示关闭 MyBatis-Plus 启动时的 banner 标志,一般用于关闭启动时的 ASCII 艺术字。
这里配置了 MyBatis-Plus 的全局配置,其中的 banner 设置为 false,
Mubatis-Plus 为简单的 CRUD 功能提供了现成的实现方案,而无需我们做太多的编码工作:
功能 | 接口 |
---|---|
新增 | int insert(T t) |
删除 | int deleteById(Serializable id) |
修改 | int updateById(T) |
根据 id 查询 | T selectById(Serializable id) |
查询全部 | List<T> selectList() |
分页查询 | IPage<T> selectPage(IPage<T> page) |
按条件查询 | IPage<T> selectPage(Wrapper<T> queryWrapper) |
这些接口我们在接下来和后续的内容中会一一遇到。
引入 maven 依赖
<dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.4.2</version> <!-- 3.5.1 -->
</dependency>
如果你使用的是阿里云的 spring initializer ,你可以在直接去选择 myabtis-plus 。
定义实体类,并标注注解
@Data // 这是 lombok 的注解,和 mybatis-plus 无关
@TableName("department") // 表名注解
public class Department {// 主键列注解。支持丰富主键策略(AUTO、NONE、INPUT、ASSIGN_ID、ASSIGN_UUID)@TableId(value = "id", type = IdType.AUTO)private Long id;// 普通列注解@TableField(value = "name", jdbcType = JdbcType.VARCHAR)private String name;@TableField(value = "location", jdbcType = JdbcType.VARCHAR)private String location;}
定义 Mapper 接口,要求继承自特定父接口
public interface DepartmentDao extends BaseMapper<Department> {
}
因为我们的自定义接口继承了 mybatis-plus 的接口,因此我们的接口中自然『天生就有』若干方法。
使用 @MapperScan 注解,扫描 mapper 接口所在位置
@SpringBootApplication
@MapperScan(basePackages = "com.example.mybatisplusdemo.outlet.dao")
public class MybatisPlusDemoApplication {...
}
[!info] 提示
或者,在每一个 Dao 接口上标注 @Mapper 也可以,这样就不需要 @MapperScan 。@Mapper 注解和 @MapperScan 注解二选一。
验证
@Resource
private DepartmentDao dao;@Test
public void demo1() {Wrapper<Department> eq = new QueryWrapper<Department>().eq("id", 1L);System.out.println(dao.selectOne(eq));
}