mybatisplus使用的基本步骤
MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生,在以往,我们使用ssm搭建一个项目,需要大量的使用到mapper文件,在里面编写简单或者复杂的sql语句,但是使用了mybatis-plus之后呢,就不用这么做了,只需要进行简单的调用即可,因为它帮我们封装好了,那下面来看下如何使用它吧~
1.创建数据库mp
使用navicat工具即可创建。2.创建user表
CREATE TABLE `user` ( `user_id` int(11) unsigned NOT NULL COMMENT '用户id\r\n', `user_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT '用户名', `user_pass` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT '用户密码', `user_nickname` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT '用户昵称', `user_email` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT '' COMMENT '用户邮箱', `user_url` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT '' COMMENT '用户网址', `user_avatar` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '用户头像', `user_last_login_ip` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '上一次登录ip', `user_register_time` datetime DEFAULT NULL COMMENT '注册时间', `user_last_login_time` datetime DEFAULT NULL COMMENT '最近登录时间', `user_status` int(1) unsigned DEFAULT '1' COMMENT '用户状态', `version` int(255) DEFAULT '1' COMMENT '乐观锁', `deleted` int(255) DEFAULT '0' COMMENT '逻辑删除', PRIMARY KEY (`user_id`), UNIQUE KEY `user_name` (`user_name`), UNIQUE KEY `user_email` (`user_email`)) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
3.编写项目,使用springboot初始化
4.导入依赖
mysqlgroupId> mysql-connector-javaartifactId> dependency> com.baomidougroupId> mybatis-plus-boot-starterartifactId> 3.4.1version> dependency> org.projectlombokgroupId> lombokartifactId> trueoptional> dependency> dependencies>mysqlmysql-connector-javacom.baomidoumybatis-plus-boot-starter3.4.1org.projectlomboklomboktrue
5.连接数据库
在springboot配置文件application.properties中配置即可,内容如下:#需要注意的是,当mysql版本为5.7时,驱动名称需要去掉cj,然后在spring.datasource.urlspring.datasource.url内容也不用加上时区,也就是去掉&serverTimezone=GMT%2B8&serverTimezone=GMT%2B8spring.datasource.username=rootspring.datasource.password=123456spring.datasource.url=jdbc:mysql://localhost:3306/bloginitial?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
接下来编写实体类,需要注意的是,在类体里面的注解暂时可忽略,因为那是后面演示乐观锁,逻辑删除、自动填充才需要使用到的:
package com.lhh.entity;import com.baomidou.mybatisplus.annotation.*;import lombok.AllArgsConstructor;import lombok.Data;import lombok.NoArgsConstructor;import lombok.ToString;import java.sql.Timestamp;import java.util.Date;@AllArgsConstructor@NoArgsConstructor@ToString@Datapublic class User { private int userId; private String userName; private String userPass; private String userNickname; private String userEmail; private String userUrl; private String userAvatar; private String userLastLoginIp; @TableLogic//逻辑删除 private Integer deleted; @Version private Integer version; @TableField(fill = FieldFill.INSERT)//用户注册的时候,自动填充 private Date userRegisterTime; @TableField(fill = FieldFill.INSERT_UPDATE)//更新的时候,自动填充 private Date userLastLoginTime;}
按照ssm的套路,接下来就是写dao(mapper),service等业务逻辑了,但是在mp当中,就不需要,只需要写一个mapper接口,继承BaseMapper,填充范型,并且接口的内容为空,那么就代表mybatis-plus默认帮我们写好了基本的crud操作,而且连service层都不用了,就是这么简单哦~
package com.lhh.mapper;import com.baomidou.mybatisplus.core.mapper.BaseMapper;import com.lhh.entity.User;import org.springframework.stereotype.Repository;@Repositorypublic interface UserMapper extends BaseMapper { //继承了BaseMapper代表所有的CRUD就已经写完了。}
注意点,我们需要在主启动类上扫描我们的mapper接口,添加内容 @MapperScan("com.lhh.mapper")
package com.lhh.mybatis_plus;import org.mybatis.spring.annotation.MapperScan;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication@MapperScan("com.lhh.mapper")public class MybatisPlusApplication { public static void main(String[] args) { SpringApplication.run(MybatisPlusApplication.class, args); }}
6.测试
那么接下来,基本的搭建工作就已经做完了,下面进行对应的测试即可。
/** * 查询所有用户 * * @param [] * @return void * @author HaiHui * @date 2021/1/11 21:50*/ @Test void contextLoads() { List users = userMapper.selectList(null); users.forEach(System.out::println); }
/** * 插入一条数据 * * @param [] * @return void * @author HaiHui * @date 2021/1/11 21:50 */ @Test void textInsert() { User user = new User(); user.setUserId(5); user.setUserName("海辉呀"); user.setUserEmail("[email protected]"); user.setUserPass("456123"); userMapper.insert(user); }
/** * 更新一条数据 * * @param [] * @return void * @author HaiHui * @date 2021/1/11 21:50 */ @Test void textUpdate() { User user = new User(); User user1 = userMapper.selectById(5); /*UpdateWrapper userUpdateWrapper = new UpdateWrapper<>();*/ user1.setUserName("海辉饿"); userMapper.update(user1, null); }
/** * 按条件查询,动态sql * * @param [] * @return void * @author HaiHui * @date 2021/1/11 21:53 */ @Test void selectByMap() { HashMap hashMap = new HashMap<>(); hashMap.put("user_id", 1); hashMap.put("user_name", "admin1"); List users = userMapper.selectByMap(hashMap); users.forEach(System.out::println); }
/** * 测试分页查询 * * @param [] * @return void * @author HaiHui * @date 2021/1/11 21:59 */ @Test void testPage() { Page page = new Page<>(2, 2); Page userPage = userMapper.selectPage(page, null); page.getRecords().forEach(System.out::println); System.out.println(page.getTotal()); }
/** * 测试删除 * * @param [] * @return void * @author HaiHui * @date 2021/1/11 22:06 */ @Test void testDelete() { //userMapper.deleteById(1);//通过id删除 //userMapper.deleteBatchIds(Arrays.asList(1,2,3));//批量删除 HashMap hashMap = new HashMap<>(); hashMap.put("user_name", "admin1"); userMapper.deleteByMap(hashMap);//通过map实现动态删除,如果要叠加多个条件,只需要多put几次即可。 }
开始使用条件构造器
/** * 查询name不为空,并且邮箱不为空的,且id大于2 * * @param * @return * @author HaiHui * @date 2021/1/11 22:58 */ @Test void wrapperTest1() { // QueryWrapper userQueryWrapper = new QueryWrapper<>(); userQueryWrapper .isNotNull("user_email") .isNotNull("user_name") .ge("user_id", 2); userMapper.selectList(userQueryWrapper).forEach(System.out::println); }
/** * 查询name不为空,并且邮箱不为空的,且id等于2 * * @param [] * @return void * @author HaiHui * @date 2021/1/11 23:08 */ @Test void wrapperTest2() { QueryWrapper userQueryWrapper = new QueryWrapper<>(); userQueryWrapper .isNotNull("user_email") .isNotNull("user_name") .eq("user_id", 2); User user = userMapper.selectOne(userQueryWrapper); System.out.println(user); }
/** * 介于什么之间查询 * * @param [] * @return void * @author HaiHui * @date 2021/1/11 23:08 */ @Test void wrapperTest3() { QueryWrapper userQueryWrapper = new QueryWrapper<>(); userQueryWrapper.between("user_id", 0, 3); Integer integer = userMapper.selectCount(userQueryWrapper); System.out.println(integer); }
/** * 模糊查询 * * @param [] * @return void * @author HaiHui * @date 2021/1/11 23:14 */ @Test void wrapperTest4() { QueryWrapper userQueryWrapper = new QueryWrapper<>(); userQueryWrapper.notLike("user_name", "ab") .likeRight("user_email", "zhangsan");//代表zhangsan右边可以是任意 Integer integer = userMapper.selectCount(userQueryWrapper); System.out.println(integer); }
至此,增删改查的基本操作已经完成,下面再简单介绍一下性能分析插件
1.导入maven依赖
p6spygroupId> p6spyartifactId> 3.9.1version>dependency>
2.编写配置文件application.properties
spring.datasource.username=rootspring.datasource.password=123456#spring.datasource.url=jdbc:mysql://localhost:3306/mp?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8#spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driverspring.datasource.url=jdbc:p6spy:mysql://localhost:3306/mp?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8spring.datasource.driver-class-name=com.p6spy.engine.spy.P6SpyDriver#配置日志mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImplmybatis-plus.global-config.db-config.logic-delete-field=deletedmybatis-plus.global-config.db-config.logic-delete-value=1mybatis-plus.global-config.db-config.logic-not-delete-value=0#spy配置#3.2.1以上使用modulelist=com.baomidou.mybatisplus.extension.p6spy.MybatisPlusLogFactory,com.p6spy.engine.outage.P6OutageFactory#3.2.1以下使用或者不配置#modulelist=com.p6spy.engine.logging.P6LogFactory,com.p6spy.engine.outage.P6OutageFactory# 自定义日志打印logMessageFormat=com.baomidou.mybatisplus.extension.p6spy.P6SpyLogger#日志输出到控制台appender=com.baomidou.mybatisplus.extension.p6spy.StdoutLogger# 使用日志系统记录 sql#appender=com.p6spy.engine.spy.appender.Slf4JLogger# 设置 p6spy driver 代理deregisterdrivers=true# 取消JDBC URL前缀useprefix=true# 配置记录 Log 例外,可去掉的结果集有error,info,batch,debug,statement,commit,rollback,result,resultset.excludecategories=info,debug,result,commit,resultset# 日期格式dateformat=yyyy-MM-dd HH:mm:ss# 实际驱动可多个#driverlist=org.h2.Driver# 是否开启慢SQL记录outagedetection=true# 慢SQL记录标准 2 秒outagedetectioninterval=2
3.打开测试类进行测试
至此,mybatis-plus的基础知识到这就为止了。