SpringBoot快速集成MyBatis-plus---(第一篇)_springboot 集成 mybatis-plus yml-程序员宅基地

技术标签: spring boot  java  mybatis  mysql  SpringBoot-MyBatisPlus  

SpringBoot整合Mybatis-plus

git项目地址 完整版

1.创建项目

首先我们需要创建一个SpringBoot创建,我使用的是maven构建SpringBoot项目.在这里我们就不贴图了

2.导入SpringBoot以及其他的依赖

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.3.1</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.22</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.16</version>
        </dependency>
    </dependencies>

<build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>

        </plugins>
        <!--生产xml-->
        <!-- 如果不添加此节点mybatis的mapper.xml文件都会被漏掉。 -->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.yml</include>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.yml</include>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                    <include>**/*.html</include>
                    <include>**/*.css</include>
                    <include>**/*.js</include>
                    <include>**/*.*</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>

​ 注:我用得mysql为 5.7版本的你们可根据自身版本挑选依赖

2.1创建SpringBoot启动类

public static void main(String[] args) throws Exception{
    
        Long s1 = System.currentTimeMillis();
        ConfigurableApplicationContext application = SpringApplication.run(MybatisApplication.class, args);
        Long s2 = System.currentTimeMillis();

        Environment env = application.getEnvironment();
        String ip = InetAddress.getLocalHost().getHostAddress();
        String port = env.getProperty("server.port");
        String path = env.getProperty("server.servlet.context-path");

        System.out.println("=======================================>");
        System.out.println("启动耗时=======>"+(s2-s1));
        System.out.println("Local:http://localhost:" + port + path);
        System.out.println("serve start-up success");
        System.out.println("=======================================>");
    }

2.2创建yml文件

#配置端口号
server:
  port: 8085


#配置数据库连接
spring:
  datasource:
#配置的数据源为druid
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/gxhserve?UseSSL=true&characterEncoding=UTF-8&UseUnicode=true
    username: root
    password: 123456



#配置MybatisPlus
mybatis-plus:
  global-config:
    #关闭启动MybatisPlus自带的banner图
    banner: false
  #配置扫描xml资源路径
  mapper-locations: classpath*:com/gxh/modules/**/xml/*Mapper.xml
  #自动驼峰映射
  configuration:
    map-underscore-to-camel-case: true

2.3 MybatisPlusConfig

/***
 * @author gxh
 * @date 2021-8-21
 */

@Configuration
@MapperScan(value = {
    "com.gxh.modules.**.mapper*"})
public class MybatisPlusConfig {
    

    /**
     *  分页插件  MybatisPlus提供的分页
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
    
        // 设置sql的limit为无限制,默认是500
        return new PaginationInterceptor().setLimit(-1);
    }

}

贴出我的目录结构

在这里插入图片描述

测试运行

1.创建一张表
id username password
1 admin 123456
2.创建实体
package com.gxh.modules.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.io.Serializable;
import java.util.Objects;

@TableName("sys_user")//mybatisPlus 注解:映射表名
@Data// lombok代码简化注解,包装Get/Set/构造器
public class SysUser implements Serializable {
    

    private Integer id;

    private String username;

    private String password;


    /**
     * 重写父类Object 提供的 toString方法,方便测试
     * @return
     */
    @Override
    public String toString() {
    
        return "SysUser{" +
                "id='" + id + '\'' +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }

    @Override
    public boolean equals(Object o) {
    
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        SysUser sysUser = (SysUser) o;
        return Objects.equals(id, sysUser.id) &&
                Objects.equals(username, sysUser.username) &&
                Objects.equals(password, sysUser.password);
    }

    @Override
    public int hashCode() {
    
        return Objects.hash(id, username, password);
    }
}
3.创建Dao(Mapper)层接口---------------映射xml文件
package com.gxh.modules.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.gxh.modules.entity.SysUser;

//                                              BaseMapper 是MyBatisPlus提供
public interface SysUserMapper extends BaseMapper<SysUser> {
    
}

<?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接口-->
<mapper namespace="com.gxh.modules.mapper.SysUserMapper">

</mapper>
4创建业务层及其实现类
package com.gxh.modules.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.gxh.modules.entity.SysUser;

public interface ISysUserService extends IService<SysUser> {
    
}
package com.gxh.modules.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxh.modules.entity.SysUser;
import com.gxh.modules.mapper.SysUserMapper;
import com.gxh.modules.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
//lombok 提供的注解简化,  简化了多个 @Autowired / @Resource
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SysUserServiceImpl
        extends ServiceImpl<SysUserMapper, SysUser>
        implements ISysUserService {
    

    //切记使用lombok 注入方式,必须private final 修饰,否则引起注入空指针
    private final SysUserMapper sysUserMapper;
}
5创建控制器并测试执行
package com.gxh.modules.controller;
import com.gxh.modules.entity.SysUser;
import com.gxh.modules.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.websocket.server.PathParam;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/sys/user")
//lombok 提供的注解简化,  简化了多个 @Autowired / @Resource
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SysUserController {
    

    //切记使用lombok 注入方式,必须private final 修饰,否则引起注入空指针
    private final ISysUserService sysUserService;


    @GetMapping("/{id}")
    public Map<String,Object> queryUserById(@PathVariable("id") Integer id){
    
        Map<String,Object> infoMap = new HashMap<>();
        SysUser sysUser = this.sysUserService.getById(id);
        infoMap.put("user",sysUser);
        return infoMap;
    }

    @GetMapping("/list")
    public Map<String,Object> userList(){
    
        Map<String,Object> infoMap = new HashMap<>();
        List<SysUser> users = this.sysUserService.list();
        infoMap.put("userList",users);
        return infoMap;
    }
}

测试图示

在这里插入图片描述
在这里插入图片描述

最终工程结构

在这里插入图片描述

到此结束,以上就是SpringBoot和mybatis-plus的整合过程,关于其中的一些实战开发中的用法下期在讲解
SpringBoot快速集成MyBatis-plus—(第二篇)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_45798917/article/details/119839578

智能推荐

Vue图片加载错误、图片加载失败的处理_swipe-vue中 加载图片失败-程序员宅基地

文章浏览阅读1.3k次。Vue图片加载错误、图片加载失败的处理注意:onerror前面要用冒号 :注意看logo定义的格式,符号不要写错了<img :src="pic?pic:'../../assets/placeholder.png'" :onerror="errorImage" alt=""> <script>export default { data() { return { errorImage: 'this.src="' _swipe-vue中 加载图片失败

fprintf用法解析-程序员宅基地

文章浏览阅读1w次,点赞6次,收藏26次。int fprintf ( FILE * stream, const char * format, ... );描述:写格式化的数据流将格式指向的C字符串写入流中。 如果格式包含格式说明符(以%开头的子序列),则格式化后的其他参数将被格式化并插入结果字符串中,替换其各自的说明符。在格式参数之后,函数至少需要格式指定的附加参数。参数:stream指向标识输出流的FIL_fprintf

Hibernate4不自动建表_hibernate 4 自动创建 表-程序员宅基地

文章浏览阅读940次。 hibernate.dialect=org.hibernate.dialect.MySQLDialect hibernate.hbm2ddl.auto=create hibernate.show_sql=true h_hibernate 4 自动创建 表

MAC下检查是否安装command line tools 工具_怎么查看mac有没有已安装command-line-tool-程序员宅基地

文章浏览阅读1.6w次。怎样判断「Command Line Tools」是否已经安装了呢?由 Sean.Lv 发布于 2013年10月26日 无人欣赏。升级到OS X Mavericks和Xcode5之后迷茫了,不知道「Command Line Tools」装了没?是否需要单独安装?猜你喜欢:怎样判断「Command Line Tools」是否已经安装了呢?_怎么查看mac有没有已安装command-line-tool

vue-baidu-map路书实现轨迹回放_bml-lushu-程序员宅基地

文章浏览阅读4.1k次,点赞2次,收藏7次。通过vue-baidu-map中路书来实现的,bml-lushu是用来还原行进轨迹的组件。_bml-lushu

SeetaFace2 测试_seetanet-程序员宅基地

文章浏览阅读4.5k次。核心网络 SeetaNetc++版,开源,是动态库,应该无源码有模型侧脸时关键点完全不对了,同时检测人脸有误检i7 1070 gpu 18ms,关键点 几乎0mscpu几乎一样,最快的还是ncnn的mtcnn,效果还更好。路径:SeetaFace2用cmake gui生成就可以。https://github.com/jacke121/SeetaFace2..._seetanet

随便推点

Django models存储json格式的数据_django数据库存json-程序员宅基地

文章浏览阅读4.9k次,点赞3次,收藏9次。JSONField官网介绍用于存储JSON格式数据的字段。在Python中,数据以其Python本机格式表示:字典,列表,字符串,数字,布尔值和None。一个可选的JSON格式类序列化的数据类型不是由标准JSON序列(支持的datetime,uuid等)。例如,您可以使用 DjangoJSONEncoder该类或任何其他json.JSONEncoder子类。JSONField使用..._django数据库存json

AXIS 访问webservice-程序员宅基地

文章浏览阅读385次。第一:先导入axis 的jar 包importorg.apache.axis.client.Call;importorg.apache.axis.client.Service;importorg.apache.axis.encoding.XMLType;第二:实际代码String url ="http://ip:1205/ws/OA.asm...

将我的ASP.NET网站从.NET 2.2 Core Preview 2升级到.NET 2.2 Core Preview 3-程序员宅基地

文章浏览阅读113次。I've recently returned from a month in South Africa and I was looking to unwind while the jetlagged kids sleep. I noticed that .NET Core 2.2 Preview 3 came out while I wasn't paying attention. My podc..._microsoft.aspnetcore.razor.design 从2.2.0降级到2.2.0-preview3-35497

联想危险!74 岁的创始人柳传志站了出来-程序员宅基地

文章浏览阅读5.1k次。&#13; &#13;&#13; &#13;&#13; &#13; &#13; 点击上方“CSDN”,选择“置顶公众号”关键时刻,第一时间送达中兴危机之时,76 岁的创始人侯为贵携..._联想出事博客

java awt_为AWT的机器人创建DSL-程序员宅基地

文章浏览阅读91次。java awt Java SDK附带了java.awt.Robot类,该类允许键盘和鼠标输入的自动化以及屏幕捕获的创建。 当您要编写一个模拟用户输入的小型测试应用程序时,或者只想自动化一些重复文本的输入时,此功能非常有用。 但是您不想每次都编写一个完整的Java应用程序。 另一方面,ANTLR是解析器生成器,使我们能够创建“特定于域的语言”(DSL)。 借助ANTLR,我们可以开发一个简单的..._createscreencapture的4个参数

关于Python的WEB开发框架的介绍_关于python web-程序员宅基地

文章浏览阅读5.1k次。一、DjangoDjango Django is oriented to programmers who deal mainly with content. The makers of Django are from the newspaper business. They say that they were often asked to implement certain features on their web site with tight deadlines. So they wrote the_关于python web