创建一个新项目,总会有引入依赖的问题,特此记录最新mybatis_plus的常用用法,以便以后快速创建项目。
大家入门学习的话,建议去官网哦。–> 官网教程
1、新建SpringBoot(2.6.6)项目并导入依赖提示1、mysql驱动
- spring boot 2.0(内置mysql -jdbc-5.x驱动),驱动类使用;
- spring boot 2.1及以上(内置mysql-jdbc-8.x驱动),驱动类使用;mysql-8向下兼容,因此使用内置版本(8.0.28)
提示2、连接的url
- mysql8.0版本连接url需要添加时区
- mysql5.0: jdbc:mysql://localhost:3306/mybatis_plus?characterEncoding=utf-8&useSSL=false
- mysql8.0: jdbc:mysql://localhost:3306/mybatis_plus?characterEncoding=utf-8&useSSL=false
&serverTimezone=GMT%2B8
<dependencies>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-generatorartifactId>
<version>3.5.1version>
dependency>
<dependency>
<groupId>org.freemarkergroupId>
<artifactId>freemarkerartifactId>
<version>2.3.31version>
dependency>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-boot-starterartifactId>
<version>3.5.1version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<scope>runtimescope>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starterartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
dependencies>
建库(mybatis-plus)、建表(user)、插入可 *** 作性数据。
CREATE DATABASE `mybatis_plus` DEFAULT CHARACTER SET utf8mb4;
USE `mybatis_plus`;
DROP TABLE IF EXISTS t_user;
CREATE TABLE t_user(
uid BIGINT(20) NOT NULL COMMENT '主键ID',
name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
age INT(11) NULL DEFAULT NULL COMMENT '年龄',
email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
create_time TIMESTAMP DEFAULT NULL COMMENT '创建时间',
update_time TIMESTAMP DEFAULT NULL COMMENT '更新时间',
deleted TINYINT(1) DEFAULT 0 COMMENT '删除标识符',
PRIMARY KEY (uid)
)ENGINE = INNODB DEFAULT CHARSET = utf8;
2、mybatis-plus代码生成工具,逆向生成代码。
/**
* @Author : WuMing
* @Description :
*/
public class FastAutoGeneratorTest {
public static void main(String[] args) {
FastAutoGenerator.create("jdbc:mysql:///mybatis_plus? characterEncoding=utf-8&userSSL=false",
"root", "123456")
.globalConfig(builder -> {
builder.author("wuming") // 设置作者
// .enableSwagger() // 开启 swagger 模式
.fileOverride() // 覆盖已生成文件
.outputDir("D:\WuMing\WsyyStudy\mybatisplus\src\main\java"); // 指定输出目录
}).packageConfig(builder -> {
builder.parent("com.tjau") // 设置父包名
.moduleName("mybatisplus") // 设置父包模块名
.pathInfo(Collections.singletonMap(OutputFile.mapperXml, "D:\WuMing\WsyyStudy\mybatisplus\src\main\resources\mapper")); // 设置mapperXml生成路径
}).strategyConfig(builder -> {
builder.addInclude("t_user") // 设置需要生成的表名
.addTablePrefix("t_"); // 设置过滤表前缀
}).templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker 引擎模板,默认的是Velocity引擎模板
.execute();
}
}
执行完后,生成如何下代码
application.yml
spring:
# 配置数据源信息
datasource:
# 配置数据源类型
type: com.zaxxer.hikari.HikariDataSource
# 配置连接数据库信息
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/mybatis_plus?serverTimezone=GMT%2B8&characterEncoding=utf-8&useSSL=false
username: root
password: 123456
mybatis-plus:
configuration:
# 配置MyBatis日志
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
global-config:
db-config:
logic-delete-field: deleted # 全局逻辑删除的实体字段名
logic-delete-value: 1 # 逻辑已删除值(默认为 1)
logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)
4、实体类配置主键生成策略和createTime和updateTime
4.1、实体类标注主键@TableId, 字段自动填充@TableField(fill = FieldFill.INSERT)
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@TableName("t_user") //对应数据库的表名
public class User implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键ID
*/
@TableId //表示该字段为主键,使用主键默认增长策略。
private Long uid;
/**
* 姓名
*/
private String name;
/**
* 年龄
*/
private Integer age;
/**
* 邮箱
*/
private String email;
/**
* 创建时间
*/
@TableField(fill = FieldFill.INSERT) //当插入数据时自动填充
private LocalDateTime createTime;
/**
* 更新时间
*/
@TableField(fill = FieldFill.UPDATE) //当更新时自动填充
private LocalDateTime updateTime;
/**
* 删除标识符
*/
private Integer deleted; //配置文件中,配饰逻辑删除标识符 阿里编码规范不建议 isXX定义标识字段
}
方法二:在配置文件中设置,如果你的所有数据表名都是以t_开头的话,可以全局统一设置,个人认为使用@TableName注解会更加灵活。
# 配置MyBatis日志
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
global-config:
db-config:
# 1-2 配置MyBatis-Plus *** 作表的默认前缀
table-prefix: t_
4.2、重写字段自动填充规则
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
//放入实体类对应的字段
@Override
public void insertFill(MetaObject metaObject) {
log.info("start insert fill ....");
this.strictInsertFill(metaObject, "createTime", LocalDateTime::now, LocalDateTime.class);
}
@Override
public void updateFill(MetaObject metaObject) {
log.info("start update fill ....");
this.strictUpdateFill(metaObject, "updateTime", LocalDateTime::now, LocalDateTime.class);
}
}
5、基本的CRUD方法-(只放入常用的实现方法)
@SpringBootTest
class ApplicationTests {
@Autowired
private UserMapper userMapper;
/**
* 增加
*/
@Test
public void insert(){
for (int i = 1; i < 10; i++) {
User user = new User();
user.setName("zhangsang");
user.setAge(i);
user.setEmail("zhangsang@qq.com");
int result = userMapper.insert(user);
System.out.println(result);
}
}
/**
* 删除
*/
@Test
public void delete(){
// 场景一:id删除
// UPDATE t_user SET deleted=1 WHERE uid = ? AND deleted=0
// int result = userMapper.deleteById(1516980881333538818L);
// System.out.println(result);
// 场景二:批量删除
// UPDATE t_user SET deleted=1 WHERE uid IN ( ? , ? , ? ) AND deleted=0
List<Long> idList = Arrays.asList(1516980881333538818L, 1516980881316761601L, 1516980881304178690L);
int result = userMapper.deleteBatchIds(idList);
System.out.println(result); // 影响条数 2
}
/**
* 修改
*/
@Test
public void update(){
// 场景一: 封装实体类修改
// User user = User.builder()
// .uid(1516980880263991297L)
// .name("李四")
// .email("lisi@qq.com")
// .age(32)
// .build();
// int result = userMapper.updateById(user);
// System.out.println(result);
// 场景二:满足条件的修改
// UPDATE t_user SET name=?, age=?, email=?, update_time=? WHERE deleted=0 AND (name LIKE ? AND age > ? OR update_time IS NULL)
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.like("name", "李四")
.gt("age", 10)
.or()
.isNull("update_time");
User user = new User(); user.setAge(18);
user.setEmail("user@atguigu.com");
user.setName("lisi");
int result = userMapper.update(user, queryWrapper);
System.out.println("受影响的行数:" + result);
}
/**
* 查询
*/
@Test
public void selectAll(){
// 场景一:根据id查询
// SELECT uid,name,age,email,create_time,update_time,deleted FROM t_user WHERE uid=? AND deleted=0
// User user1 = userMapper.selectById(1516980880263991297L);
// System.out.println(user1);
// 场景二:根据条件查询(Map)
// SELECT uid,name,age,email,create_time,update_time,deleted FROM t_user WHERE name = ? AND age = ? AND deleted=0
// Map map = new HashMap<>();
// map.put("age", 22);
// map.put("name", "admin");
// List list = userMapper.selectByMap(map);
// list.forEach(System.out::println);
// 场景三:查询多条
// SELECT uid,name,age,email,create_time,update_time,deleted FROM t_user WHERE uid IN ( ? , ? ) AND deleted=0
// List idList = Arrays.asList(1516980880263991297L, 1516980881228681217L);
// List list = userMapper.selectBatchIds(idList);
// list.forEach(System.out::println);
// 场景四:包装类条件查询
// SELECT uid,name,age,email,create_time,update_time,deleted FROM t_user WHERE deleted=0
// AND (name LIKE ? AND age BETWEEN ? AND ? AND email IS NOT NULL) ORDER BY age DESC,uid ASC
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.like("name", "李四")
.between("age", 9, 40)
.isNotNull("email")
.orderByDesc("age") //倒序
.orderByAsc("uid");
List<User> list = userMapper.selectList(queryWrapper);
System.out.println(list);
// 场景五:查询所有
// SELECT uid,name,age,email,create_time,update_time,deleted FROM t_user WHERE deleted=0
// List list = userMapper.selectList(null);
// list.forEach(System.out::println);
}
}
6、如何使用内置分页插件和自定义分页插件
6.1、首先编写分页插件组件
//可以将主类中的注解移到此处
@Configuration
@MapperScan("com.atguigu.mybatisplus.mapper")
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}
6.2、编写UserMapper接口和UserMapper.xml
UserMapper.java
@Repository
public interface UserMapper extends BaseMapper<User> {
/**
*根据年龄查询用户列表,分页显示
*param page分页对象,Xml中可以从里面进行取值,传递参数Page即自动分页,必须放在第一位
*@param age 年龄
*return
*/
Page<User> selectPageVo(@Param("page") Page<User> page, @Param("age") Integer age);
}
UserMapper.xml
<mapper namespace="com.tjau.mybatisplus.mapper.UserMapper">
<sql id="BaseColumns">uid, `name`, age, email, insert_time, update_timesql>
<select id="selectPageVo" resultType="com.tjau.mybatisplus.entity.User">
SELECT <include refid="BaseColumns"/> FROM t_user WHERE age > # {age}
select>
mapper>
6.3、两种分页实现
/**
* 分页方式二: 使用自定义分页
*/
@Test
public void selectPageByCondition(){
//设置分页参数
Page<User> page = new Page<>(1,5);
userMapper.selectPageVo(page,20);
// 获取分页数据
List<User> list = page.getRecords();
list.forEach(System.out::println);
System.out.println("当前页:"+page.getCurrent());
System.out.println("每页显示的条数:"+page.getSize());
System.out.println("总记录数:"+page.getTotal());
System.out.println("总页数:"+page.getPages());
System.out.println("是否有上一页:"+page.hasPrevious());
System.out.println("是否有下一页:"+page.hasNext());
}
/**
* 分页方式一: 使用内置分页分页
*/
@Test
public void selectPage(){
//设置分页参数
Page<User> page = new Page<>(1,5);
userMapper.selectPage(page,null);
// 获取分页数据
List<User> list = page.getRecords();
list.forEach(System.out::println);
System.out.println("当前页:"+page.getCurrent());
System.out.println("每页显示的条数:"+page.getSize());
System.out.println("总记录数:"+page.getTotal());
System.out.println("总页数:"+page.getPages());
System.out.println("是否有上一页:"+page.hasPrevious());
System.out.println("是否有下一页:"+page.hasNext());
}
**注 **
以上是基础的mp常用使用方法。希望对您有所帮助。mybatis-plus更适合单表 *** 作,如果涉及到复杂查询和多表查询,建议通过xml编写sql来实现。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)