文章目錄
- 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));
}