MyBatisPlus从入门到精通
1. 概述
MybatisPlus是一款Mybatis增强工具,用于简化开发,提高效率。 它在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
2.快速入门
2.0 准备工作
①准备数据
CREATE TABLE `user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
`user_name` varchar(20) NOT NULL COMMENT '用户名',
`password` varchar(20) NOT NULL COMMENT '密码',
`name` varchar(30) DEFAULT NULL COMMENT '姓名',
`age` int(11) DEFAULT NULL COMMENT '年龄',
`address` varchar(100) DEFAULT NULL COMMENT '地址',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
insert into `user`(`id`,`user_name`,`password`,`name`,`age`,`address`) values
(1,'ruiwen','123','瑞文',12,'山东'),(2,'gailun','1332','盖伦',13,'平顶山'),
(3,'timu','123','提姆',22,'蘑菇石'),(4,'daji','1222','妲己',221,'狐山');
②创建SpringBoot工程
添加依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.0</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
创建启动类
@SpringBootApplication
public class SGApplication {
public static void main(String[] args) {
SpringApplication.run(SGApplication.class);
}
}
③准备实体类
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private Long id;
private String userName;
private String password;
private String name;
private Integer age;
private String address;
}
2.1 使用MybatisPlus
①添加依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
②配置数据库信息
spring:
datasource:
url: jdbc:mysql://localhost:3306/mpstudy?useSSL=false&characterEncoding=utf-8&serverTimezone=UTC
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
③创建Mapper接口
创建Mapper接口继承BaseMapper接口
public interface UserMapper extends BaseMapper<User> {
}
BaseMapper接口中已经提供了很多常用方法。所以我们只需要直接从容器中获取Mapper就可以进行操作了,不需要自己去编写Sql语句。
④配置Mapper扫描
在启动类上配置我们的Mapper在哪个包。
@SpringBootApplication
@MapperScan("com.sangeng.mapper")
public class SGApplication {
public static void main(String[] args) {
SpringApplication.run(SGApplication.class);
}
}
⑤获取Mapper进行测试
@SpringBootTest
public class MPTest {
@Autowired
private UserMapper userMapper;
@Test
public void testQueryList() {
List<User> users = userMapper.selectList(null);
System.out.println(users);
}
}
标签:COMMENT,MybatisPlus,name,boot,private,class,学习,笔记,public
From: https://www.cnblogs.com/xu1feng/p/18384991