MybatisPlus自定义SQL用法

这篇具有很好参考价值的文章主要介绍了MybatisPlus自定义SQL用法。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

1、功能概述?

MybatisPlus框架提供了BaseMapper接口供我们使用,大大的方便了我们的基础开发,但是BaseMapper中提供的方法很多情况下不够用,这个时候我们依旧需要自定义SQL,也就是跟mybatis的用法相同,自定义xml映射文件。

本案例提供了三种比较经典的操作:查询全部数据/QueryWrapper使用方式/模糊查询

2、MyBatis-Plus概述

MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

【技术储备】

拥有 Java 开发环境以及相应 IDE

熟悉 Spring Boot

熟悉 Maven

2.1、Mybatis-plus特性

 

无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑

损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作

强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求

支持 Lambda 形式调用:通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错

支持主键自动生成:支持多达 4 种主键策略(内含分布式唯一 ID 生成器 - Sequence),可自由配置,完美解决主键问题

支持 ActiveRecord 模式:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可进行强大的 CRUD 操作

支持自定义全局通用操作:支持全局通用方法注入( Write once, use anywhere )

内置代码生成器:采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 层代码,支持模板引擎,更有超多自定义配置等您来使用

内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通 List 查询

分页插件支持多种数据库:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer 等多种数据库

内置性能分析插件:可输出 SQL 语句以及其执行时间,建议开发测试时启用该功能,能快速揪出慢查询

内置全局拦截插件:提供全表 delete 、 update 操作智能分析阻断,也可自定义拦截规则,预防误操作

2.2、数据库支持

任何能使用 MyBatis 进行 CRUD, 并且支持标准 SQL 的数据库,具体支持情况如下,如果不在下列表查看分页部分教程 PR 您的支持。

MySQL,Oracle,DB2,H2,HSQL,SQLite,PostgreSQL,SQLServer,Phoenix,Gauss ,ClickHouse,Sybase,OceanBase,Firebird,Cubrid,Goldilocks,csiidb,informix,TDengine,redshift

达梦数据库,虚谷数据库,人大金仓数据库,南大通用(华库)数据库,南大通用数据库,神通数据库,瀚高数据库,优炫数据库,星瑞格数据库

3、创建MybatisPlus -查询全部数据

3.1、工程结构

mybatisplus自定义sql,MybatisPlus框架,Mybatisplus,mybatisplus使用

3.2、在IDEA中选择默认配置

选择默认的springboot配置+Lombok+mysql

mybatisplus自定义sql,MybatisPlus框架,Mybatisplus,mybatisplus使用

3.3、工程的pom.xml文件

主要的包信息:springboot2.7.16+ mybatis-plus-boot-starter3.5.3.2+ mysql-connector-java5.1.42

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.16</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>mybatisplussql</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>mybatisplussql</name>
    <description>mybatisplussql</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <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>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.3.2</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.42</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>

        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
    </build>

</project>

3.4、创建数据库和表信息

CREATE DATABASE mybatisplus;

USE mybatisplus;

CREATE TABLE student(

   stu_id VARCHAR(50),

   stu_name VARCHAR(30),

   stu_sex VARCHAR(2),

   stu_age VARCHAR(4),

   stu_addr VARCHAR(50),

   stu_pwd VARCHAR(50)

)DEFAULT CHARSET=utf8;

INSERT INTO student VALUES('1001','晓春','男','33','安徽合肥','1001');

INSERT INTO student VALUES('1002','陈平安','男','18','安徽合肥','1002');

3.5、application.yml配置信息

主要配置数据库连接和修改mybatisplus默认配置信息:

log-impl控制台打印出mybatis执行时的具体sql、查询条件、返回值等

map-underscore-to-camel-case:mybatisplus在查询数据库的时候回默认的开启数据库下划线驼峰命名转化,我们需要关闭。

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/mybatisplus
    username: root
    password: 123456
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    map-underscore-to-camel-case: false
  # 配置在src/main/java classpath:/com/*/*/mapper/*Mapper.xml
  # 配置在resource classpath:/mapper/**.xml
  mapper-locations: classpath:/com/*/*/mapper/**.xml

3.6、创建bean对象

@TableId("stu_id")该属性如果不写,会导致mybatisplus中根据id查询数据的方法无法使用。

@TableName("student"):如果类名与表明相同,该属性可以不写

@Data
@AllArgsConstructor
@NoArgsConstructor
//定义映射数据表明,如果名称相同可以不写
@TableName("student")
public class Student {
    //定义student表主键
    @TableId("stu_id")
    private String stu_id;
    private String stu_name;
    private String stu_sex;
    private String stu_age;
    private String stu_addr;
    private String stu_pwd;
}

3.7、创建Mapper映射文件

MybatisPlus默认的配置文件是放在Resources下的mapper文件中。我们通过配置放在src目录下

具体配置在application.yml文件中:

mapper-locations: classpath:/com/*/*/mapper/**.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.example.mybatisplussql.mapper.StudentMapper">
    <select id="findAll" resultType="com.example.mybatisplussql.bean.Student">
        select * from student
    </select>
</mapper>

3.8、映射文件配置注意点

如果映射文件配置在src的目录下,需要在pom文件中配置xml文件放行

<build >
<resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.xml</include>
            </includes>
        </resource>
    </resources>
</build>

3.9、创建mapper接口

我们在创建接口的时候,需要遵循一些规范,规范如下:

规范1、接口的方法名称与映射文件中的id相同

规范2、接口的传入参数类型与parameterType相同,没有传入参数不写。

规范3、接口的传输参数类型与resultType类型相同,resultType中只写单条数据的数据类型。

规范4、映射文件的namespace与接口的全限定名称相同。

public interface StudentMapper extends BaseMapper<Student> {
public  List<Student>  findAll();
}

3.10、在启动类中配置扫描mapper文件

@SpringBootApplication
@MapperScan("com.example.mybatisplussql.mapper")
public class MybatisplussqlApplication {
    public static void main(String[] args) {
        SpringApplication.run(MybatisplussqlApplication.class, args);
    }
}

3.11、创建测试类

我这个地方的测试类直接使用的是springmvc进行测试,返回json类型的数据

@Controller
public class StudentController {
    @Autowired(required = false)
    StudentMapper studentMapper;

    @RequestMapping("/findAll")
    @ResponseBody
    public List<Student> findAll(){
        List<Student> list= studentMapper.findAll();
        return list;
    }
}

3.12、返回值信息信息如下

mybatisplus自定义sql,MybatisPlus框架,Mybatisplus,mybatisplus使用

4、MybatisPlus中QueryWrapper使用方式

其他配置使用上面的即可

我们可以通过QueryWrapper定义我们需要的条件查询,映射文件中程序通过ew.customSqlSegment获取数据。

说明:本案例的优点在于,mybatisplus可以通过QueryWrapper中定义的参数,生成动态SQL

4.1、在StudentMapper.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.example.mybatisplussql.mapper.StudentMapper">
<select id="findStudentByWrapper" resultType="com.example.mybatisplussql.bean.Student">
      select * from student ${ew.customSqlSegment}
  </select>
</mapper>

4.2、在StudentMapper.java中创建接口

public interface StudentMapper extends BaseMapper<Student> {
    public List<Student> findStudentByWrapper(@Param(Constants.WRAPPER) QueryWrapper<Student> queryWrapper);
}

4.3、创建测试程序

QueryWrapper.eq:表示精准检索 

QueryWrapper.like:表示模糊检索

@Controller
public class StudentController {
    @Autowired(required = false)
    StudentMapper studentMapper;

    @RequestMapping("/findStudentByWrapper")
    @ResponseBody
    public List<Student> findStudentByWrapper(){
        QueryWrapper wrapper = new QueryWrapper<Student>()
                .eq("stu_id", "1001")
                .like("stu_name", "晓春")
                .eq("stu_sex","男");
        List<Student> list = studentMapper.findStudentByWrapper(wrapper);
        return list;
    }
}

4.4、测试后,后台SQL语句生成如下

从这个生成的语句可以看出,由于我们在QueryWrapper中给了三个条件,SQL生成中的where后就是三个条件。

mybatisplus自定义sql,MybatisPlus框架,Mybatisplus,mybatisplus使用

4.5、浏览器返回值

mybatisplus自定义sql,MybatisPlus框架,Mybatisplus,mybatisplus使用

5、根据姓名模糊查询信息

5.1、在StudentMapper.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.example.mybatisplussql.mapper.StudentMapper">

    <select id="findStudentByName" parameterType="student" resultType="student">
        select *
        from student
        where stu_name like concat('%',#{stu_name},'%')
    </select>

</mapper>

5.2、在StudentMapper.java中创建接口

public interface StudentMapper extends BaseMapper<Student> {
    //根据stu_name模糊查询数据
    public List<Student> findStudentByName(Student stu);
}

5.3、创建测试程序

@Controller
public class StudentController {
    @Autowired(required = false)
    StudentMapper studentMapper;

    @RequestMapping("/findStudentByName")
    @ResponseBody
    public List<Student> findStudentByName(){
        Student stu=new Student();
        stu.setStu_name("晓春");
        List<Student> list = studentMapper.findStudentByName(stu);
        return list;
    }
}

5.4、测试后,后台SQL语句

mybatisplus自定义sql,MybatisPlus框架,Mybatisplus,mybatisplus使用

5.5、浏览器请求返回值

mybatisplus自定义sql,MybatisPlus框架,Mybatisplus,mybatisplus使用

6、源码下载

源码下载地址:源码是vip资源,介意不要点 

https://download.csdn.net/download/tangshiyilang/88380147

 文章来源地址https://www.toymoban.com/news/detail-776658.html

 

到了这里,关于MybatisPlus自定义SQL用法的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • mybatisplus开启sql打印的三种方式

            使用mybatisplus自带的log-impl配置,可以在控制台打印出sql语句、执行结果的数据集、数据结果条数等详细信息,这种方法适合再调试的时候使用,因为这个展示的信息详细,更便于调试,查找问题进行优化。缺点就是如果执行的sql语句过多,则输出的日志就会很多,

    2024年02月05日
    浏览(46)
  • SpringBoot框架——8.MybatisPlus常见用法(常用注解+内置方法+分页查询)

    1.MybatisPlus常用注解:         1.1 当数据库、表名和字段名和实体类完全一致时无需加注解,不一致时:         @TableName指定库名         @TableId指定表名         @TableField指定字段名         1.2 自增主键:         @TableId(type=IdType.AUTO)         private Long id;        

    2024年04月26日
    浏览(32)
  • MybatisPlus存在 sql 注入漏洞(CVE-2023-25330)解决办法

    MyBatis-Plus TenantPlugin 是 MyBatis-Plus 的一个为多租户场景而设计的插件,可以在 SQL 中自动添加租户 ID 来实现数据隔离功能。 MyBatis-Plus TenantPlugin 3.5.3.1及之前版本由于 TenantHandler#getTenantId 方法在构造 SQL 表达式时默认情况下未对 tenant(租户)的 ID 值进行过滤,当程序启用了 Te

    2024年02月07日
    浏览(27)
  • MybatisPlus整合p6spy组件SQL分析

    目录  p6spy java为什么需要  如何使用 其他配置  p6spy  p6spy是一个开源项目,通常使用它来跟踪数据库操作,查看程序运行过程中执行的sql语句。 p6spy将应用的数据源给劫持了,应用操作数据库其实在调用p6spy的数据源,p6spy劫持到需要执行的sql或者hql之类的语句之后, 他自

    2024年02月12日
    浏览(33)
  • 手把手教你如何扩展(破解)mybatisplus的sql生成

    众所周知, mybatisplus 提供了强大的代码生成能力,他默认生成的常用的CRUD方法(例如插入、更新、删除、查询等)的定义,能够帮助我们节省很多体力劳动。 他的 BaseMapper 中定义了这些常用的CRUD方法,我们在使用时,继承这个 BaseMapper 类就默认拥有了这些能力。 如果我们

    2024年02月05日
    浏览(37)
  • MybatisPlus <= 3.5.3.1 TenantPlugin 组件 存在 sql 注入漏洞(CVE-2023-25330)

    MyBatis-Plus TenantPlugin 是 MyBatis-Plus 的一个为多租户场景而设计的插件,可以在 SQL 中自动添加租户 ID 来实现数据隔离功能。 MyBatis-Plus TenantPlugin 3.5.3.1及之前版本由于 TenantHandler#getTenantId 方法在构造 SQL 表达式时默认情况下未对 tenant(租户)的 ID 值进行过滤,当程序启用了 Te

    2024年02月03日
    浏览(35)
  • 使用Log4j与log4j2配置mybatisplus打印sql日志

    环境:项目非完全spring项目,没有spring的配置文件。执行sql时老是不打印sql语句。因此进行修改,过程比较坎坷,记录一下。 我尝试使用log4j和log4j2进行配置 最终把这两种全部配置记录上 Log4j配置 如果项目用的是log4j需要进行配置打印sql的步骤 首先引入log4j的包 配置一下l

    2024年02月04日
    浏览(52)
  • 使用mybatisplus查询sql时,报Error attempting to get column ‘ID‘ from result set错误

    问题描述: 在使用如下代码进行查询时,报Error attempting to get column ‘ID’ from result set错误: 首先排除数据库字段大小写问题。 然后考虑ID字段在本轮逻辑中不是很重要,对代码做了如下更改,指定了查询字段: 结果查询正常,然后能得出结果集到实体类的映射过程出现问题

    2024年02月09日
    浏览(39)
  • 关于MyBatisPlus框架下出现xml里面定义的方法无法被正确识别以及提示调用mysql存储过程时参数无效的问题

    网上很多解决方法都是查看函数名是否一致、命名空间等,但还有一种可能是你调用接口的模块本身的resource文件夹下就有一个含有xml的mapper文件夹,而这个文件夹里面不含有方法A的sql实现,如下图: 导致程序只在这个mapper里面找A的sql实现,那肯定会提示没有找到。 除了检

    2024年02月09日
    浏览(40)
  • MyBatisPlus连接SQL Server代码自动生成报com.microsoft.sqlserver.jdbc.SQLServerException: 列名 ‘TABLE_NAME‘ 无效

    列名TABLE_NAME?表单里并没有这个字段,推测是代码生成器在读取输入表单内容的时候自己拼凑了SQL语句,遇到SQL Server的时候语句出了问题。刚好做上一个项目时试过自动生成SQL Server的数据库表单代码,上一次可以正常生成,而偏偏这次出了问题。 首先想到mybatis-plus和mybat

    2024年02月12日
    浏览(32)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包