mybatis-plus使用xml自定义sql语句

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


学习准备

使用mybaits-plus配置项目好基本的三个层次 dao service controller
可以参考我的这篇文章
如何快速使用 Mybatis-plus.

前言

mybatis-plus的使用确实很方便,但我们在日常的使用中难免遇到复杂的查询
这时候应该使用xml自定义sql


提示:以下是本篇文章正文内容,下面案例可供参考

一 在Mapper层自定义方法

在这里插入图片描述
这里定义了一个根据ID查询方法

package com.example.demo.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.demo.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

@Mapper
public interface UserMapper  extends BaseMapper<User> {
    User selectUserByID(@Param("id") int id);
}

二、创建mapper.xml文件

我这里是在resources下创建了mapper文件夹
并在里面创建User.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.demo.mapper.UserMapper">

   

<!-- 注释一定要使用这种形式,不然会报错-->

<select id="selectUserByID" resultType="com.example.demo.entity.User">
select * from db01.dept where deptno = #{id}
</select>

</mapper>

三、配置YAML

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

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/db01?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false&serverTimezone=GMT%2B8
server:
  port: 8082
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.example.demo.entity

总结

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

  • 10
    点赞
  • 55
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
MyBatis-Plus 提供了丰富的自定义 SQL 查询功能,可以满足复杂的查询需求。你可以使用 `@Select` 注解或者在 XML 文件中编写自定义 SQL 查询语句。 下面是使用注解方式编写自定义 SQL 查询的示例: ```java @Mapper public interface UserMapper extends BaseMapper<User> { @Select("SELECT * FROM user WHERE age > #{age}") List<User> selectUsersByAge(@Param("age") Integer age); } ``` 在上面的示例中,我们使用 `@Select` 注解来定义了一个自定义的查询方法 `selectUsersByAge`,查询年龄大于指定年龄的用户列表。 如果你更倾向于使用 XML 文件来编写自定义 SQL 查询语句,可以创建一个与 Mapper 接口对应的 XML 文件,并在该文件中定义自定义查询语句。 例如,假设你有一个 UserMapper 接口,对应的 XML 文件为 UserMapper.xml,你可以在 XML 文件中编写如下的自定义查询语句: ```xml <mapper namespace="com.example.mapper.UserMapper"> <select id="selectUsersByAge" resultType="com.example.entity.User"> SELECT * FROM user WHERE age > #{age} </select> </mapper> ``` 需要注意的是,自定义 SQL 查询语句中可以使用参数占位符(如 `#{age}`)来传递参数,也可以使用 MyBatis-Plus 提供的 `@Param` 注解来指定参数名称。 以上是自定义 SQL 查询的简单示例,实际使用时,你可以根据具体的业务需求编写更加复杂的查询语句,并灵活运用 MyBatis-Plus 提供的查询条件构造器、动态 SQL 等功能来实现更精确的查询。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

qwecxzz

鸡腿

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

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

打赏作者

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

抵扣说明:

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

余额充值