MyBatis--入门案列
由于我们之前有MyBatis开发的基础,所以我们现在直接来一个入门案例
由于我们刚刚学完SpringBoot,所以我们现在直接使用SpringBoot来构建项目,官网的快速开始也是直接用的SpringBoot
步骤一:创建数据库和表
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,'略略略','nigger',15,'4006184000');
步骤二:创建SpringBoot工程
只用勾选MySQLDriver
步骤三:补全依赖
导入druid和Mybatis——Plus的坐标
<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>
步骤四:编写数据库
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC
username: root
password: root
步骤五:创建User实体类
@Data
@AllArgsConstructor
public class User {
private long id;
private String name;
private String password;
private Integer age;
private String tel;
}
步骤六:创建dao层接口
@Mapper
public interface UserDao extends BaseMapper<User> {
}
写到这就写完了,只能说MybatisPlus就是牛掰,但是得加一个@Mapper注解
步骤七:直接来测试
@SpringBootTest
class MPday02ApplicationTests {
@Autowired
private UserDao userDao;
@Test
void contextLoads() {
List<User> users = userDao.selectList(null);
System.out.println(users);
}
}
运行结果:
直接输出了
小结:SpringBoot集成MyBatisPlus非常简单,只需要导入MyBatisPlus的坐标,热案后零dao继承BaseMapper,写上泛型,类上方加上@Mapper注解