MyBatis-Plus--自定义SQL

原文网址:MyBatis-Plus--自定义SQL_IT利刃出鞘的博客-CSDN博客

简介

说明

本文用实例介绍MybatisPlus如何自定义SQL。

使用

自定义的sql使用Wrapper对版本有要求:mybatis-plus版本需要大于或等于3.0.7。

含义

ew.customSqlSegment

条件构造器(Wrapper)

ew.sqlSet

所设置的列

ew.sqlSelect

要select的列

特殊语句

操作实例说明
TRUNCATE@Update("TRUNCATE xxx")不要用@Delete
ALTER@Update("ALTER xxx")
DELETE@Delete("DELETE xxx")

源码

包里边定义好的常量。我们可以直接用这些常量。

mybatis-plus-core-3.3.2.jar\com\baomidou\mybatisplus\core\toolkit\Constants.class

package com.baomidou.mybatisplus.core.toolkit;

public interface Constants extends StringPool {
    String MYBATIS_PLUS = "mybatis-plus";
    String MD5 = "MD5";
    String AES = "AES";
    String AES_CBC_CIPHER = "AES/CBC/PKCS5Padding";
    String ENTITY = "et";
    String ENTITY_DOT = "et.";
    String WRAPPER = "ew";
    String WRAPPER_DOT = "ew.";
    String WRAPPER_ENTITY = "ew.entity";
    String WRAPPER_SQLSEGMENT = "ew.sqlSegment";
    String WRAPPER_EMPTYOFNORMAL = "ew.emptyOfNormal";
    String WRAPPER_NONEMPTYOFNORMAL = "ew.nonEmptyOfNormal";
    String WRAPPER_NONEMPTYOFENTITY = "ew.nonEmptyOfEntity";
    String WRAPPER_EMPTYOFWHERE = "ew.emptyOfWhere";
    String WRAPPER_NONEMPTYOFWHERE = "ew.nonEmptyOfWhere";
    String WRAPPER_ENTITY_DOT = "ew.entity.";
    String U_WRAPPER_SQL_SET = "ew.sqlSet";
    String Q_WRAPPER_SQL_SELECT = "ew.sqlSelect";
    String Q_WRAPPER_SQL_COMMENT = "ew.sqlComment";
    String Q_WRAPPER_SQL_FIRST = "ew.sqlFirst";
    String COLUMN_MAP = "cm";
    String COLUMN_MAP_IS_EMPTY = "cm.isEmpty";
    String COLLECTION = "coll";
    String WHERE = "WHERE";
    String MP_OPTLOCK_INTERCEPTOR = "oli";
    String MP_OPTLOCK_VERSION_ORIGINAL = "MP_OPTLOCK_VERSION_ORIGINAL";
    String MP_OPTLOCK_VERSION_COLUMN = "MP_OPTLOCK_VERSION_COLUMN";
    String MP_OPTLOCK_ET_ORIGINAL = "MP_OPTLOCK_ET_ORIGINAL";
    String WRAPPER_PARAM = "MPGENVAL";
    String WRAPPER_PARAM_FORMAT = "#{%s.paramNameValuePairs.%s}";
}

分页

代码

Mapper

package com.example.demo.user.mapper;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.user.entity.User;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

@Repository
public interface UserMapper extends BaseMapper<User> {
    
    // 自定义SQL的分页
    @Select("SELECT * FROM t_user ${ew.customSqlSegment}")
    IPage<User> findUser(IPage<User> page, @Param(Constants.WRAPPER) Wrapper wrapper);
}

Controller

package com.example.demo.user.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.user.entity.User;
import com.example.demo.user.mapper.UserMapper;
import com.example.demo.user.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Api(tags = "分页")
@RestController
@RequestMapping("page")
public class PageController {

    // 我为了简单直接注入mapper,项目中controller要通过service调mapper
    @Autowired
    private UserMapper userMapper;

    @ApiOperation("自定义SQL")
    @GetMapping("customSQL")
    public IPage<User> customSQLPage(Page<User> page) {
        LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery();
        wrapper.like(User::getNickName, "昵称");

        // 这样写会报错:MybatisPlusException: can not use this method for "getCustomSqlSegment"
        // LambdaQueryChainWrapper<User> wrapper = userService.lambdaQuery()
        //         .eq(User::getUserName, "sky");

        return userMapper.findUser(page, wrapper);
    }
}

测试

访问http://localhost:8080/page/customSQL

上边是文章的部分内容,为便于维护,全文已转移到此网址:MyBatis-Plus-自定义SQL - 自学精灵

### 回答1: Mybatis-plus提供了多种自定义SQL的方式,以下是其中几种常用的方式: 1. 使用@Select注解或者Mapper.xml文件中的<select>标签编写自定义SQL语句。 2. 使用@Update、@Insert、@Delete注解或者Mapper.xml文件中的<update>、<insert>、<delete>标签编写自定义SQL语句。 3. 使用Wrapper对象构建查询条件,然后调用BaseMapper的selectList()、selectOne()等方法进行查询。 4. 使用SqlHelper类提供的方法构建SQL语句,然后调用BaseMapper的selectList()、selectOne()等方法进行查询。 5. 使用自定义SQL解析器,将自定义SQL语句解析成Mybatis-plus可识别的SQL语句,然后调用BaseMapper的selectList()、selectOne()等方法进行查询。 以上是常用的几种自定义SQL的方式,具体使用哪种方式取决于具体的业务需求和个人习惯。 ### 回答2: Mybatis-plus 是一个基于 Mybatis 的增强工具,它提供了一系列解决方案,使得 Mybatis 的使用变得更加简单和高效。其中,自定义 SQLMybatis-plus 的一个重要特性,它提供了一种自由扩展 SQL 的方式,使得开发者可以通过自己的实现来满足各种灵活的需求。 要使用自定义 SQL,首先需要在 Mapper 接口中定义方法,并用 @Select 注解标注该方法。在注解中,我们可以书写 SQL 语句,如: ``` @Select("select * from user where name = #{name}") User findUserByName(@Param("name") String name); ``` 这里的 @Select 注解告诉了 Mybatis-plus,这是一个查询方法,所使用的 SQL 是 select * from user where name = #{name}。其中,#{name} 是一个占位符,Mybatis-plus 会自动将方法参数中的 name 值替换到该占位符中。 除了 @Select,Mybatis-plus 还提供了一些其他的注解,如 @Insert、@Update、@Delete 等,它们分别表示插入、更新、删除操作。类似于 @Select,这些注解也可以用自定义 SQL,声明方式都类似。 在定义完自定义 SQL 方法之后,我们就可以在业务方法中调用这些方法来实现对数据库的操作了,如: ``` User user = userMapper.findUserByName("Tom"); ``` 最后需要注意的是,虽然自定义 SQL 可以满足我们的各种需求,但是它们本身也存在一些缺点。比如它们可能会使代码可读性变低,也会存在 SQL 注入等安全问题。因此,在使用自定义 SQL 的时候,需要谨慎考虑,遵循安全和可读性原则来编写。 ### 回答3: MyBatis-Plus 是一个基于 MyBatis 的增强工具,在其基础上,提供了更加强大和便捷的操作。在使用 MyBatis-Plus 进行数据库操作时,很多情况下需要编写自定义SQL 语句来满足特定的需求,因此,学习如何自定义 SQL 语句是非常必要的。 MyBatis-Plus 支持多种方式自定义 SQL,以下分别介绍: 1. @Select 注解 @Select 注解可以在方法上加入 SQL 语句,执行时会使用该 SQL 语句进行查询。例如: @Select("select * from user where id = #{id}") User selectById(Long id); 2. XML 映射文件 在 MyBatis-Plus 配置文件中,可以配置 XML 映射文件的位置和名称,然后在 XML 文件中书写 SQL 语句,例如: <select id="selectById" resultType="com.example.model.User"> select * from user where id = #{id} </select> 3. 自定义接口 自定义接口是将 SQL 语句封装在方法中最为常用的方式,只需定义一个接口并继承 MyBatis-Plus 提供的 BaseMapper 接口,然后在接口中定义方法即可。例如: public interface UserMapper extends BaseMapper<User> { @Select("select * from user where username = #{username}") User selectByUsername(String username); } 4. 自定义 SQL 语句构建器 MyBatis-Plus 提供了 LambdaQueryWrapper 和 QueryWrapper 等构建器来方便编写 SQL 语句,若这些构建器无法满足我们的需求,可以自定义 SQL 语句构建器。例如: public class CustomWrapper<T> extends AbstractWrapper<T, CustomWrapper<T>> { public CustomWrapper() { super(); } public CustomWrapper(T entity) { super.setEntity(entity); } public CustomWrapper(T entity, String... columns) { super.setEntity(entity); super.select(columns); } public CustomWrapper<T> myMethod(String field, Object value) { super.eq(field, value); return this; } } 以上就是 MyBatis-Plus 自定义 SQL 的几种方式,选择哪种方式取决于个人需求和习惯。无论是哪种方式,都需要注意 SQL 注入的风险,保证 SQL 语句的安全性。
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IT利刃出鞘

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值