一、
1.1
-
MybatisPlus(简称MP)是基于MyBatis框架基础上开发的增强型工具,旨在简化开发、提供效率。
-
开发方式
-
基于MyBatis使用MyBatisPlus
-
基于Spring使用MyBatisPlus
-
-
create database if not exists mybatisplus_db character set utf8; use mybatisplus_db; CREATE TABLE user ( id bigint(20) primary key auto_increment, name varchar(32) not null, password varchar(32) not null, age int(3) not null , tel varchar(32) not null ); insert into user values(1,'Tom','tom',3,'18866668888'); insert into user values(2,'Jerry','jerry',4,'16688886666'); insert into user values(3,'Jock','123456',41,'18812345678'); insert into user values(4,'传智播客','itcast',15,'4006184000');
步骤2:创建SpringBoot工程
说明:
-
由于MP并未被收录到idea的系统内置配置,无法直接选择加入,需要手动在pom.xml中配置添加
步骤4:pom.xml补全依赖
<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.1</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.16</version> </dependency>
说明:
-
druid数据源可以加也可以不加,SpringBoot有内置的数据源,可以配置成使用Druid数据源
-
spring: datasource: type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/mybatisplus_db?serverTimezone=UTC username: root password: root
说明:==serverTimezone是用来设置时区,UTC是标准时区,和咱们的时间差8小时,所以可以将其修改为Asia/Shanghai
==
步骤6:根据数据库表创建实体类
public class User { private Long id; private String name; private String password; private Integer age; private String tel; //setter...getter...toString方法略 }
步骤7:创建Dao接口
@Mapper public interface UserDao extends BaseMapper<User>{ }
@SpringBootApplication //@MapperScan("com.itheima.dao") public class Mybatisplus01QuickstartApplication { public static void main(String[] args) { SpringApplication.run(Mybatisplus01QuickstartApplication.class, args); } }
说明:Dao接口要想被容器扫描到,有两种解决方案:
-
方案一:在Dao接口上添加
@Mapper
注解,并且确保Dao处在引导类所在包或其子包中-
该方案的缺点是需要在每一Dao接口中添加注解
-
-
方案二:在引导类上添加
@MapperScan
注解,其属性为所要扫描的Dao所在包-
@Mapper
就可以不写。
-
@SpringBootTest class MpDemoApplicationTests { @Autowired private UserDao userDao; @Test public void testGetAll() { List<User> userList = userDao.selectList(null); System.out.println(userList); } }
说明:
userDao注入的时候下面有红线提示的原因是什么?
-
UserDao是一个接口,不能实例化对象
-
只有在服务器启动IOC容器初始化后,由框架创建DAO接口的代理对象来注入
-
现在服务器并未启动,所以代理对象也未创建,IDEA查找不到对应的对象注入,所以提示报红
-
一旦服务启动,就能注入其代理对象,所以该错误提示不影响正常运行。
查看运行结果:
文章评论