广告
返回顶部
首页 > 资讯 > 精选 >SpringBoot整合Mybatis-plus怎么使用
  • 416
分享到

SpringBoot整合Mybatis-plus怎么使用

2023-06-30 05:06:18 416人浏览 八月长安
摘要

今天小编给大家分享一下SpringBoot整合mybatis-plus怎么使用的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。

今天小编给大家分享一下SpringBoot整合mybatis-plus怎么使用的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。

一、mybatis-plus简介:

Mybatis-Plus(简称MP)是一个 Mybatis 的增强工具,在 Mybatis 的基础上只做增强不做改变,为简化开发、提高效率而生。这是官方给的定义,关于mybatis-plus的更多介绍及特性,可以参考mybatis-plus官网。那么它是怎么增强的呢?其实就是它已经封装好了一些crud方法,我们不需要再写xml了,直接调用这些方法就行,就类似于JPA。并且3.X系列支持lambda语法,让我在写条件构造的时候少了很多的"魔法值",从代码结构上更简洁了.

二、springboot整合mybatis-plus案例

pom.xml配置

<dependencies>    <dependency>      <groupId>org.springframework.boot</groupId>      <artifactId>spring-boot-starter</artifactId>    </dependency>    <!--springboot程序测试依赖,如果是自动创建项目默认添加-->    <dependency>      <groupId>org.springframework.boot</groupId>      <artifactId>spring-boot-starter-test</artifactId>      <scope>test</scope>    </dependency>    <dependency>      <groupId>org.projectlombok</groupId>      <artifactId>lombok</artifactId>      <version>1.16.10</version>      <scope>provided</scope>    </dependency>    <!-- 包含spirng mvc ,Tomcat的包包含requestMapping restController 等注解 -->    <dependency>      <groupId>org.springframework.boot</groupId>      <artifactId>spring-boot-starter-WEB</artifactId>    </dependency>    <dependency>      <groupId>com.alibaba</groupId>      <artifactId>druid-spring-boot-starter</artifactId>      <version>1.1.10</version>    </dependency>    <dependency>      <groupId>mysql</groupId>      <artifactId>Mysql-connector-java</artifactId>    </dependency>    <!-- druid依赖 -->    <dependency>      <groupId>com.alibaba</groupId>      <artifactId>druid</artifactId>      <version>1.1.0</version>    </dependency>    <!-- mybatisPlus 核心库 -->    <dependency>      <groupId>com.baomidou</groupId>      <artifactId>mybatis-plus-boot-starter</artifactId>      <version>3.1.0</version>    </dependency>  </dependencies>

application.yml配置

server:  port: 10100   #  配置启动端口号 mybatis:  config-location: classpath:mybatis.cfg.xml    #  mybatis主配置文件所在路径  type-aliases-package: com.demo.drools.entity  #  定义所有操作类的别名所在包  mapper-locations:                                     #  所有的mapper映射文件    - classpath:mapper@Data@TableName("user_info")//@TableName中的值对应着表名public class UserInfoEntity {        @TableId(type = IdType.AUTO)    private Long id;        private String name;        private Integer age;        private String skill;        private String evaluate;        private Long fraction;}

config类

package com.demo.drools.config; import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;import com.baomidou.mybatisplus.extension.plugins.PerfORManceInterceptor;import org.springframework.context.annotation.Bean; public class MybatisPlusConfig {        @Bean    public PerformanceInterceptor performanceInterceptor() {        return new PerformanceInterceptor();    }        @Bean    public PaginationInterceptor paginationInterceptor() {        return new PaginationInterceptor();    }}

Spring Boot启动类

package com.demo.drools; import org.mybatis.spring.annotation.MapperScan;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication//@MapperScan和dao层添加@Mapper注解意思一样@MapperScan(basePackages = "com.demo.drools.dao")public class DroolsApplication {    public static void main(String[] args) {        SpringApplication.run(DroolsApplication.class, args);    }}

dao层

package com.demo.drools.dao; import com.baomidou.mybatisplus.core.mapper.BaseMapper;import com.baomidou.mybatisplus.core.metadata.IPage;import com.demo.drools.entity.UserInfoEntity;import org.apache.ibatis.annotations.Mapper;import org.apache.ibatis.annotations.Param; @Mapperpublic interface UserInfoDao extends BaseMapper<UserInfoEntity> {   }

service层

package com.demo.drools.service; import com.baomidou.mybatisplus.core.metadata.IPage;import com.baomidou.mybatisplus.extension.service.IService;import com.demo.drools.entity.UserInfoEntity; public interface UserInfoService extends IService<UserInfoEntity> {    }

serviceImpl实现类层

package com.demo.drools.service.impl; import com.baomidou.mybatisplus.core.metadata.IPage;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;import com.demo.drools.dao.UserInfoDao;import com.demo.drools.entity.UserInfoEntity;import com.demo.drools.service.UserInfoService;import org.springframework.stereotype.Service; import javax.annotation.Resource; @Servicepublic class UserInfoSerivceImpl extends ServiceImpl<UserInfoDao, UserInfoEntity> implements UserInfoService {    }

controller控制层

package com.demo.drools.controller; import com.baomidou.mybatisplus.core.metadata.IPage;import com.baomidou.mybatisplus.extension.plugins.pagination.Page;import com.demo.drools.entity.UserInfoEntity;import com.demo.drools.service.UserInfoService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList;import java.util.Collection;import java.util.HashMap;import java.util.List;import java.util.Map; @RestController@RequestMapping("/userInfo")public class UserInfoController {    @Autowired    private UserInfoService userInfoService;            @RequestMapping("/getInfo")    public UserInfoEntity getInfo(String userId){        UserInfoEntity userInfoEntity = userInfoService.getById(userId);        return userInfoEntity;    }        @RequestMapping("/getList")    public List<UserInfoEntity> getList(){        List<UserInfoEntity> userInfoEntityList = userInfoService.list();        return userInfoEntityList;    }        @RequestMapping("/getInfoListPage")    public IPage<UserInfoEntity> getInfoListPage(){        //需要在Config配置类中配置分页插件        IPage<UserInfoEntity> page = new Page<>();        page.setCurrent(5); //当前页        page.setSize(1);    //每页条数        page = userInfoService.page(page);        return page;    }        @RequestMapping("/getListMap")    public Collection<UserInfoEntity> getListMap(){        Map<String,Object> map = new HashMap<>();        //kay是字段名 value是字段值        map.put("age",20);        Collection<UserInfoEntity> userInfoEntityList = userInfoService.listByMap(map);        return userInfoEntityList;    }        @RequestMapping("/saveInfo")    public void saveInfo(){        UserInfoEntity userInfoEntity = new UserInfoEntity();        userInfoEntity.setName("小龙");        userInfoEntity.setSkill("JAVA");        userInfoEntity.setAge(18);        userInfoEntity.setFraction(59L);        userInfoEntity.setEvaluate("该学生是一个在改BUG的码农");        userInfoService.save(userInfoEntity);    }        @RequestMapping("/saveInfoList")    public void saveInfoList(){        //创建对象        UserInfoEntity sans = new UserInfoEntity();        sans.setName("Sans");        sans.setSkill("睡觉");        sans.setAge(18);        sans.setFraction(60L);        sans.setEvaluate("Sans是一个爱睡觉,并且身材较矮骨骼巨大的骷髅小胖子");        UserInfoEntity papyrus = new UserInfoEntity();        papyrus.setName("papyrus");        papyrus.setSkill("JAVA");        papyrus.setAge(18);        papyrus.setFraction(58L);        papyrus.setEvaluate("Papyrus是一个讲话大声、个性张扬的骷髅,给人自信、有魅力的骷髅小瘦子");        //批量保存        List<UserInfoEntity> list =new ArrayList<>();        list.add(sans);        list.add(papyrus);        userInfoService.saveBatch(list);    }        @RequestMapping("/updateInfo")    public void updateInfo(){        //根据实体中的ID去更新,其他字段如果值为null则不会更新该字段,参考yml配置文件        UserInfoEntity userInfoEntity = new UserInfoEntity();        userInfoEntity.setId(1L);        userInfoEntity.setAge(19);        userInfoService.updateById(userInfoEntity);    }        @RequestMapping("/saveOrUpdateInfo")    public void saveOrUpdate(){        //传入的实体类userInfoEntity中ID为null就会新增(ID自增)        //实体类ID值存在,如果数据库存在ID就会更新,如果不存在就会新增        UserInfoEntity userInfoEntity = new UserInfoEntity();        userInfoEntity.setId(1L);        userInfoEntity.setAge(20);        userInfoService.saveOrUpdate(userInfoEntity);    }        @RequestMapping("/deleteInfo")    public void deleteInfo(String userId){        userInfoService.removeById(userId);    }        @RequestMapping("/deleteInfoList")    public void deleteInfoList(){        List<String> userIdlist = new ArrayList<>();        userIdlist.add("12");        userIdlist.add("13");        userInfoService.removeByIds(userIdlist);    }        @RequestMapping("/deleteInfoMap")    public void deleteInfoMap(){        //kay是字段名 value是字段值        Map<String,Object> map = new HashMap<>();        map.put("skill","删除");        map.put("fraction",10L);        userInfoService.removeByMap(map);    }}

controller层用到lambda语法

 package com.demo.drools.controller; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;import com.baomidou.mybatisplus.core.metadata.IPage;import com.baomidou.mybatisplus.extension.plugins.pagination.Page;import com.demo.drools.entity.UserInfoEntity;import com.demo.drools.service.UserInfoService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestMapping; import java.util.HashMap;import java.util.List;import java.util.Map; public class UserInfoPlusController {    @Autowired    private UserInfoService userInfoService;            @RequestMapping("/getInfoListPlus")    public Map<String,Object> getInfoListPage(){        //初始化返回类        Map<String,Object> result = new HashMap<>();        //查询年龄等于18岁的学生        //等价sql: SELECT id,name,age,skill,evaluate,fraction FROM user_info WHERE age = 18        QueryWrapper<UserInfoEntity> queryWrapper1 = new QueryWrapper<>();        queryWrapper1.lambda().eq(UserInfoEntity::getAge,18);        List<UserInfoEntity> userInfoEntityList1 = userInfoService.list(queryWrapper1);        result.put("studentAge18",userInfoEntityList1);        //查询年龄大于5岁的学生且小于等于18岁的学生        //等价SQL: SELECT id,name,age,skill,evaluate,fraction FROM user_info WHERE age > 5 AND age <= 18        QueryWrapper<UserInfoEntity> queryWrapper2 = new QueryWrapper<>();        queryWrapper2.lambda().gt(UserInfoEntity::getAge,5);        queryWrapper2.lambda().le(UserInfoEntity::getAge,18);        List<UserInfoEntity> userInfoEntityList2 = userInfoService.list(queryWrapper2);        result.put("studentAge5",userInfoEntityList2);        //模糊查询技能字段带有"画"的数据,并按照年龄降序        //等价SQL: SELECT id,name,age,skill,evaluate,fraction FROM user_info WHERE skill LIKE '%画%' ORDER BY age DESC        QueryWrapper<UserInfoEntity> queryWrapper3 = new QueryWrapper<>();        queryWrapper3.lambda().like(UserInfoEntity::getSkill,"画");        queryWrapper3.lambda().orderByDesc(UserInfoEntity::getAge);        List<UserInfoEntity> userInfoEntityList3 = userInfoService.list(queryWrapper3);        result.put("studentAgeSkill",userInfoEntityList3);        //模糊查询名字带有"小"或者年龄大于18的学生        //等价SQL: SELECT id,name,age,skill,evaluate,fraction FROM user_info WHERE name LIKE '%小%' OR age > 18        QueryWrapper<UserInfoEntity> queryWrapper4 = new QueryWrapper<>();        queryWrapper4.lambda().like(UserInfoEntity::getName,"小");        queryWrapper4.lambda().or().gt(UserInfoEntity::getAge,18);        List<UserInfoEntity> userInfoEntityList4 = userInfoService.list(queryWrapper4);        result.put("studentOr",userInfoEntityList4);        //查询评价不为null的学生,并且分页        //等价SQL: SELECT id,name,age,skill,evaluate,fraction FROM user_info WHERE evaluate IS NOT NULL LIMIT 0,5        IPage<UserInfoEntity> page = new Page<>();        page.setCurrent(1);        page.setSize(5);        QueryWrapper<UserInfoEntity> queryWrapper5 = new QueryWrapper<>();        queryWrapper5.lambda().isNotNull(UserInfoEntity::getEvaluate);        page = userInfoService.page(page,queryWrapper5);        result.put("studentPage",page);        return result;    }}

以上就是mybatis-plus的小案例,mybatis-plus它像我之前使用的spring data jpa框架不用写sql语句,就可以实现简单的增删改查、批量操作、分页mybatis-plus功能还是比较强大,能减少我们写很多代码,我个人还是比较喜欢用这个mybatis-plus的

mybatis-plus只是mybatis的增强版,它不影响mybatis的使用,我们可以写我们自定的方法以及sql,接下来我们看一个小案例

dao层新增方法

    IPage<UserInfoEntity> selectUserInfoByGtFraction(            @Param(value = "page") IPage<UserInfoEntity> page,            @Param(value = "fraction")Long fraction);

service新增方法

    IPage<UserInfoEntity> selectUserInfoByGtFraction(IPage<UserInfoEntity> page,Long fraction);

serviceImpl层新增方法

    IPage<UserInfoEntity> selectUserInfoByGtFraction(IPage<UserInfoEntity> page,Long fraction);

controller层新增方法

     @RequestMapping("/getInfoListSQL")    public IPage<UserInfoEntity> getInfoListSQL(){        //查询大于60分以上的学生,并且分页        IPage<UserInfoEntity> page = new Page<>();        page.setCurrent(1);        page.setSize(5);        page = userInfoService.selectUserInfoByGtFraction(page,60L);        return page;    }

配置我们的mybatis的xml

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "Http://mybatis.org/dtd/mybatis-3-mapper.dtd" ><mapper namespace="com.demo.drools.dao.UserInfoDao">  <!-- Sans 2019/6/9 14:35 -->  <select id="selectUserInfoByGtFraction" resultType="com.demo.drools.entity.UserInfoEntity">    SELECT * FROM user_info WHERE fraction > #{fraction}    </select></mapper>

以上配置就是我们的mybatis用法。

mybatis plus强大的条件构造器queryWrapper、updateWrapper

QueryWrapper: Entity 对象封装操作类
2.UpdateWrapper : Update 条件封装,用于Entity对象更新操作
3.条件构造器使用中的各个方法格式和说明

SpringBoot整合Mybatis-plus怎么使用

以上就是“SpringBoot整合Mybatis-plus怎么使用”这篇文章的所有内容,感谢各位的阅读!相信大家阅读完这篇文章都有很大的收获,小编每天都会为大家更新不同的知识,如果还想学习更多的知识,请关注编程网精选频道。

--结束END--

本文标题: SpringBoot整合Mybatis-plus怎么使用

本文链接: https://www.lsjlt.com/news/327527.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作