赞
踩
Mybatis本来就是简化JDBC操作的,而MyBatis-Plus就是简化MyBatis的,是一个 MyBatis的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。其官网地址为:https://mp.baomidou.com/
我们将通过一个简单的 Demo 来阐述 MyBatis-Plus 的强大功能,在此之前,我们假设您已经:
- 拥有 Java 开发环境以及相应 IDE
- 熟悉 Spring Boot
- 熟悉 Maven
创建user表
DROP TABLE IF EXISTS user;
CREATE TABLE `user` (
`id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`name` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '姓名',
`age` int DEFAULT NULL COMMENT '年龄',
`email` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '邮箱',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
往user表插入数据
DELETE FROM user;
INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, 'test1@baomidou.com'),
(2, 'Jack', 20, 'test2@baomidou.com'),
(3, 'Tom', 28, 'test3@baomidou.com'),
(4, 'Sandy', 21, 'test4@baomidou.com'),
(5, 'Billie', 24, 'test5@baomidou.com');
创建springBoot的web项目,导入依赖
<!-- 数据库驱动的包--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!-- lombok的包,为了实体类偷懒--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <!-- mybatis-plus的依赖,导入这个就不需要mybatis的包了--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.0.5</version> </dependency>
连接数据库yml配置
spring:
datasource:
username: root
password: password
url: jdbc:mysql://localhost:3306/study?userSSL=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
driver-class-name: com.mysql.cj.jdbc.Driver
实体类User
package com.lingaolu.bean; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class User { private Long id; private String name; private Integer age; private String email; }
书写interface接口文件,继承BaseMapper,至此所有的curd已经编写我完成,就可以使用了,不需要mapper.xml文件
package com.lingaolu.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.lingaolu.bean.User;
public interface UserMapper extends BaseMapper<User> {
}
主启动类添加扫描mapper接口的注解,根据自己目录而定
@MapperScan("com.lingaolu.mapper")
单元测试
package com.lingaolu; import com.lingaolu.bean.User; import com.lingaolu.mapper.UserMapper; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.util.List; @SpringBootTest class MybatisPlusApplicationTests { @Autowired private UserMapper userMapper; @Test void contextLoads() { List<User> userList = userMapper.selectList(null); userList.forEach(System.out::println); } }
单元测试结果
想看日志的可以配置日志控制台输出
mybatis-plus:
configuration:
# 配置日志控制台输出
log-impl: org.apache.ibatis.logging.stdout.StdOutImp
MyBatis-Plus默认的主键生成策略是IdType .ID_WORKER,使用的是雪花算法要想插入主键自增,需要
- 数据库主键设置自增
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。