1.引入坐标
<!-- springBoot--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <!-- mysql驱动--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <!--修改版本--> <version>5.1.38</version> <scope>runtime</scope> </dependency> <!-- mybatisplus启动器--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.5.1</version> </dependency> <!-- lombok用于简化实体类开发--> <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> <!--Druid 阿里连接池坐标--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.10</version> </dependency>
2.配置springboot的配置文件 application.yml
#服务端口 server: port: 8080 #数据源配置 spring: datasource: type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/mybatis_plus?useUnicode=true&characterEncoding=utf-8&useSSL=true username: root password: #mybatis配置 #mybatis: # type-aliases-package: com.bdqn.pojo # mapper-locations: classpath:/mapper/*.xml mybatis-plus: configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # mapper-locations: classpath:/mapper/*.xml # 设置myabtisplus全局配置 global-config: db-config: # 来设置表的实体类的统一前缀 table-prefix: t_ id-type: auto #设置别名 type-aliases-package: com.bdqn.pojo type-enums-package: com.bdqn.enums # 统一设置主键的生成策略 logging: level: org: springframework: boot: autoconfigure: ERROR
前三个必须引用 后面的按需引入 看个人喜好
3.创建实体类
package com.bdqn.pojo; import com.baomidou.mybatisplus.annotation.*; import com.bdqn.enums.SexEnum; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.ToString; import org.springframework.beans.factory.annotation.Autowired; @NoArgsConstructor @AllArgsConstructor @Data @ToString 设置实体类的表名 //@TableName("t_user") public class User { //将我们的属性所对应的字段指定为主键 //tableid注解的value的属性用于指定主键的字段 //tbaleud注解的type用于设置主键生成策略 // @TableId(value = "uid" ,type = IdType.AUTO) @TableId("uid") private Long uid; // 用于指定属性所对应的字段名 @TableField("user_name ") private String name; private int age; private String email; private SexEnum sex; //是否删除 0 代表未删除 1代表删除 @TableLogic @TableField("is_deleted") private int isdeleted; }
4.创建mapper接口,继承BsaeMapper
package com.bdqn.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.bdqn.pojo.User; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; import java.util.Map; @Repository @Mapper public interface UserMapper extends BaseMapper<User> { }
5.创建测试类 test
package com.bdqn.test; import com.bdqn.mapper.UserMapper; import com.bdqn.pojo.User; import org.apache.ibatis.annotations.Mapper; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import javax.sound.midi.Soundbank; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; @SpringBootTest public class MbatisPlusTest { @Autowired UserMapper userMapper; /** * 查询所有 */ @Test public void testselectList(){ //通过条件构造器查询一个list集合 若没有条件,则可以设置为null为参数 List<User> users = userMapper.selectList(null); users.forEach(System.out::println); } /** *添加 */ @Test public void testinsert(){ User user = new User(); // user.setUid(100l); user.setName("张三"); user.setAge(18); user.setEmail("zhangsanqq@.com"); int row = userMapper.insert(user); System.out.println("row:"+row); System.out.println(user.getUid()); } /** * 删除 */ @Test public void textDel(){ //根据id删除 // int i = userMapper.deleteById(1518880319707545601L); // System.out.println("row=" +i); //根据map集合删除 // HashMap<String, Object> map = new HashMap<>(); // map.put("name" ,"张三"); // map.put("age","18"); // int i = userMapper.deleteByMap(map); // System.out.println("row ="+i); //批量删除 List<Long> list = Arrays.asList(100l, 101l, 102l); userMapper.deleteBatchIds(list); System.out.println("row ="+list); } /** * 修改 */ @Test public void testUpdate(){ User user = new User(); user.setUid(4l); user.setName("lisi"); user.setEmail("list@qq.con"); userMapper.updateById(user); } /** * 根据id查询所有 */ @Test public void testselebyid(){ //根据id查询所有 //SELECT id,name,age,email FROM user WHERE id=? // userMapper.selectById(1l); //根据多个id查询多个用户 批量查询 // List<Long> list = Arrays.asList(1l, 2l, 3l); // List<User> users = userMapper.selectBatchIds(list); // users.forEach(System.out::println ); // Map<String, Object> map = new HashMap<>(); // map.put("name ","Jack"); // map.put("age",20); // userMapper.selectByMap(map); } /** * 自定义接口 */ @Test public void testcont(){ Map<String, Object> map = userMapper.selectmapByid(1l); System.out.println(map); } }
6.通用 service接口
package com.bdqn.service; import com.baomidou.mybatisplus.extension.service.IService; import com.bdqn.pojo.User; public interface UserService extends IService<User> { }
实现service接口
package com.bdqn.service.impl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.bdqn.mapper.UserMapper; import com.bdqn.pojo.User; import com.bdqn.service.UserService; import org.springframework.stereotype.Service; @Service public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService { }
测试 service 通用方法
@Test public void testGetcount(){ //查询总条数 long count = userService.count(); System.out.println(count ); } @Test //批量添加 service public void testInsert(){ ArrayList<User> list = new ArrayList<>(); for (int i=1;i<10;i++){ User user = new User(); user.setName("yzs"+i); user.setAge(10+i); user.setEmail("2023620602qq@.com"+i); list.add(user); } boolean b = userService.saveBatch(list); System.out.println(b); }
7. 使用QueryWarpper、UpdateWarpper、LambdaQueryWarpper、LambdaUpdateWarpper实现增删改查
package com.bdqn.test; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; import com.bdqn.mapper.UserMapper; import com.bdqn.pojo.User; import org.junit.jupiter.api.Test; import org.junit.platform.commons.util.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.util.List; import java.util.Map; @SpringBootTest public class MbatisPlusWarmapperTest { @Autowired UserMapper userMapper; @Test public void test01(){ //查询用户信息 根据name模糊查询 查询年龄大于20小于30 邮箱不能为空 QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.like("user_name","a") .between("age",20,30) .isNotNull("email"); List<User> users = userMapper.selectList(wrapper); users.forEach(System.out::println); } @Test public void test02(){ //查询用户信息,按照年龄降序排序 若年龄相同则按照id升序排序 QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.orderByDesc("age") .orderByAsc("uid"); List<User> users = userMapper.selectList(wrapper); users.forEach(System.out::println); } @Test public void test03(){ //删除邮箱地址为空 QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.isNull("email"); int users = userMapper.delete(wrapper); System.out.println(users); } @Test public void test04(){ //将年龄大于20并且用户名包含有a 或邮箱为空的用户信息修改 User user = new User(); user.setName("小周"); QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.gt("age", "20").like("user_name","a").or().isNull("email"); int users = userMapper.update(user,wrapper) ; System.out.println(users); } @Test public void test05(){ //将用户名包含有a (年龄大于20或邮箱为空)的用户信息修改 //UPDATE t_user SET user_name =?, age=? WHERE is_deleted=0 AND (user_name LIKE ? AND (age > ? OR email IS NULL)) User user = new User(); user.setName("小阳"); user.setAge(21); QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.like("user_name","a ").and(i->i.gt("age","20").or().isNull("email")); int users = userMapper.update(user,wrapper) ; System.out.println(users); } @Test public void test06(){ //查询用户的用户名,年龄,邮箱 //UPDATE t_user SET user_name =?, age=? WHERE is_deleted=0 AND (user_name LIKE ? AND (age > ? OR email IS NULL)) User user = new User(); user.setName("小阳"); user.setAge(21); QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.select("user_name","age","email"); List<Map<String, Object>> users = userMapper.selectMaps(wrapper); users.forEach(System.out::println); } @Test public void test07(){ //查询id小于100的用户信息 //SELECT uid,user_name AS name,age,email,is_deleted FROM t_user WHERE is_deleted=0 AND (uid IN (select uid from t_user where uid<=100)) QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.inSql("uid","select uid from t_user where uid<=100"); List<User> users = userMapper.selectList(wrapper); users.forEach(System.out::println); } @Test public void test08(){ //将用户名包含有a (年龄大于20或邮箱为空)的用户信息修改 //UPDATE t_user SET user_name=?,age=? WHERE is_deleted=0 AND (user_name LIKE ? AND (age > ? OR email IS NULL)) UpdateWrapper<User> wrapper = new UpdateWrapper<>(); wrapper.like("user_name","小") .and(i->i.gt("age","20").or().isNull("email")); wrapper.set("user_name","小洲").set("age","20") ; int users = userMapper.update(null,wrapper) ; System.out.println(users); } @Test public void test09(){ //SELECT uid,user_name AS name,age,email,is_deleted FROM t_user WHERE is_deleted=0 AND (age >= ? AND age <= ?) String username="小"; Integer ageBegin=20; Integer ageEnd=30; QueryWrapper<User> wrapper = new QueryWrapper<>(); if (StringUtils.isNotBlank(username)){ //isnotblank 判断某个字符串是否不为空 不为null, 不为空白符 wrapper.like("user_name",username); } if (ageBegin!=null){ wrapper.ge("age",ageBegin); } if (ageEnd!=null){ wrapper.le("age",ageEnd); } List<User> users = userMapper.selectList(wrapper); users.forEach(System.out::println); } @Test public void test10(){ String username="小"; Integer ageBegin=20; Integer ageEnd=30; QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.like(StringUtils.isNotBlank(username),"user_name",username) .ge(ageBegin!=null,"age",ageBegin) .le(ageEnd!=null,"age",ageEnd); List<User> users = userMapper.selectList(wrapper); users.forEach(System.out::println); } @Test public void test11(){ String username="小"; Integer ageBegin=20; Integer ageEnd=30; LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>(); wrapper.like(StringUtils.isNotBlank(username),User::getName,username) .ge(ageBegin!=null,User::getAge,ageBegin) .le(ageEnd!=null,User::getAge,ageEnd); List<User> users = userMapper.selectList(wrapper); users.forEach(System.out::println); } @Test public void test12(){ //将用户名包含有a (年龄大于20或邮箱为空)的用户信息修改 //UPDATE t_user SET user_name=?,age=? WHERE is_deleted=0 AND (user_name LIKE ? AND (age > ? OR email IS NULL)) LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>(); updateWrapper.like(User::getName,"小") .and(i->i.gt(User::getAge,"20").or().isNull(User::getEmail)); updateWrapper.set(User::getName,"小洲").set(User::getAge,"20") ; int users = userMapper.update(null,updateWrapper) ; System.out.println(users); } }
8.分页插件和乐观锁悲观锁的配置即使用
package com.bdqn.config; import com.baomidou.mybatisplus.annotation.DbType; import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor; import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class MybatisplusConfig { @Bean public MybatisPlusInterceptor mybatisPlusInterceptor(){ MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); //添加分页插件 interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); //添加乐观锁插件 interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor()); return interceptor ; } }
测试分页和乐观锁悲观锁
package com.bdqn.test; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.bdqn.mapper.ProductMapper; import com.bdqn.mapper.UserMapper; import com.bdqn.pojo.Product; import com.bdqn.pojo.User; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import javax.sound.midi.Soundbank; @SpringBootTest public class MybatisPlusPluginsTest { @Autowired UserMapper userMapper; @Autowired ProductMapper productMapper; @Test public void testPage(){ //分页插件 Page<User> page = new Page<>(1,3); Page<User> userPage = userMapper.selectPage(page, null); page.getPages(); System.out.println(userPage); //还可以点很多方法 System.out.println(userPage.getRecords()); System.out.println(userPage.getPages()); System.out.println(userPage.getTotal()); System.out.println(userPage.hasNext()); System.out.println(userPage.hasPrevious()); } @Test public void testPageVo(){ Page<User> page = new Page<>(1, 3); Page<User> userPage = userMapper.selectPageVo(page, 20); System.out.println(userPage.getRecords()); System.out.println(userPage.getPages()); System.out.println(userPage.getTotal()); System.out.println(userPage.hasNext()); System.out.println(userPage.hasPrevious()); } @Test public void testProduct01(){ //小李查询商品价格 Product productli = productMapper.selectById(1); System.out.println("小李查询的商品价格:"+productli.getPrice()); //小王查询商品价格 Product productwang = productMapper.selectById(1); System.out.println("小王查询的商品价格:"+productwang.getPrice()); // 小李将商品价格+50 productli.setPrice(productli.getPrice()+50); productMapper.updateById(productli); // 小王将商品价格-30 productwang.setPrice(productwang.getPrice()-30); int row = productMapper.updateById(productwang); if (row==0){ // 操作失败,重试 Product productnew = productMapper.selectById(1); productnew.setPrice(productnew.getPrice()-30); productMapper.updateById(productnew); } //老板查询商品价格 Product productlaoban = productMapper.selectById(1); System.out.println("老板查询的商品价格:"+productlaoban.getPrice()); } }
9.通用枚举
-
实体类添加 enums sex
-
创建 SexEnum枚举
package com.bdqn.enums; import com.baomidou.mybatisplus.annotation.EnumValue; import lombok.Getter; @Getter public enum SexEnum { MALE(1,"男"), FEMALE(2,"女 "); @EnumValue//将注解所标识的属性的值存储到数据库中 private Integer sex; private String sexName; SexEnum(Integer sex, String sexName) { this.sex = sex; this.sexName = sexName; } }
测试枚举
package com.bdqn.test; import com.bdqn.enums.SexEnum; import com.bdqn.mapper.UserMapper; import com.bdqn.pojo.User; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest public class MybatisPlusEnumTeat { @Autowired UserMapper userMapper; @Test public void Test01(){ User user = new User(); user.setName("小粥"); user.setAge(21); user.setSex(SexEnum.MALE); int insert = userMapper.insert(user); System.out.println("添加成功"+insert ); } }