mybatis参数输入 #{}和${}

news2025/2/27 21:14:31

1、建库建表

CREATE DATABASE `mybatis-example`;
 
USE `mybatis-example`;
 
CREATE TABLE `t_emp`(
  emp_id INT AUTO_INCREMENT,
  emp_name CHAR(100),
  emp_salary DOUBLE(10,5),
  PRIMARY KEY(emp_id)
);
 
INSERT INTO `t_emp`(emp_name,emp_salary) VALUES("tom",200.33);
INSERT INTO `t_emp`(emp_name,emp_salary) VALUES("jerry",666.66);
INSERT INTO `t_emp`(emp_name,emp_salary) VALUES("andy",777.77);

2、pom.xml

    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
        </dependency>
 
        <!-- MySQL驱动 mybatis底层依赖jdbc驱动实现,本次不需要导入连接池,mybatis自带! -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
 
        <!--junit5测试-->
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
        </dependency>
 
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>

3、Employee.java(pojo)

package com.atguigu.mybatis.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Employee {
    private Integer empId;
    private String empName;
    private Double empSalary;
}

4、EmpMapper.java

package com.atguigu.mybatis.mapper;
import com.atguigu.mybatis.pojo.Employee;
import java.util.List;
public interface EmpMapper {

    List<Employee> getEmployeeList();

    Employee getEmployeeById(Integer empId);
    Employee getEmployeeById2(Integer empId);

    List<Employee> getEmployeeListByName(String name);
    List<Employee> getEmployeeListByName2(String name);
    List<Employee> getEmployeeListByName3(String name);

    List<Employee> getEmployeeList2(String tableName);

}

5、mybatis-config.xml(mybatis的总配置文件)

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
 
    <!-- environments表示配置Mybatis的开发环境,可以配置多个环境,在众多具体环境中,使用default属性指定实际运行时使用的环境。default属性的取值是environment标签的id属性的值。 -->
    <environments default="development">
        <!-- environment表示配置Mybatis的一个具体的环境 -->
        <environment id="development">
            <!-- Mybatis的内置的事务管理器 -->
            <transactionManager type="JDBC"/>
            <!-- 配置数据源 -->
            <dataSource type="POOLED">
                <!-- 建立数据库连接的具体信息 -->
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis-example"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
 
    <mappers>
        <!-- Mapper注册:指定Mybatis映射文件的具体位置 -->
        <!-- mapper标签:配置一个具体的Mapper映射文件 -->
        <!-- resource属性:指定Mapper映射文件的实际存储位置,这里需要使用一个以类路径根目录为基准的相对路径 -->
        <!--    对Maven工程的目录结构来说,resources目录下的内容会直接放入类路径,所以这里我们可以以resources目录为基准 -->
        <mapper resource="mapper/EmpMapper.xml"/>
    </mappers>
 
</configuration>

6、EmpMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- namespace等于mapper接口类的全限定名,这样实现对应 -->
<mapper namespace="com.atguigu.mybatis.mapper.EmpMapper">

    <!-- 查询使用 select标签
            id = 方法名
            resultType = 返回值类型
            标签内编写SQL语句
     -->
    <select id="getEmployeeList" resultType="com.atguigu.mybatis.pojo.Employee">
        <!-- #{empId}代表动态传入的参数,并且进行赋值!后面详细讲解 -->
        select
        emp_id empId,
        emp_name empName,
        emp_salary empSalary
        from t_emp
    </select>

    <select id="getEmployeeById" resultType="com.atguigu.mybatis.pojo.Employee">
        select
        emp_id empId,
        emp_name empName,
        emp_salary empSalary
        from t_emp
        where emp_id = #{value}
    </select>

    <!--演示 ${}的用法-->
    <select id="getEmployeeById2" resultType="com.atguigu.mybatis.pojo.Employee">
        select
        emp_id empId,
        emp_name empName,
        emp_salary empSalary
        from t_emp
        where emp_id = ${value}
    </select>

    <select id="getEmployeeListByName" resultType="com.atguigu.mybatis.pojo.Employee">
        select
        emp_id empId,
        emp_name empName,
        emp_salary empSalary
        from t_emp
        where emp_name like #{value}
    </select>

    <select id="getEmployeeListByName2" resultType="com.atguigu.mybatis.pojo.Employee">
        select
        emp_id empId,
        emp_name empName,
        emp_salary empSalary
        from t_emp
        where emp_name like ${value}
    </select>

    <select id="getEmployeeListByName3" resultType="com.atguigu.mybatis.pojo.Employee">
        select
        emp_id empId,
        emp_name empName,
        emp_salary empSalary
        from t_emp
        where emp_name like '${value}'
    </select>

    <select id="getEmployeeList2" resultType="com.atguigu.mybatis.pojo.Employee">
        select
        emp_id empId,
        emp_name empName,
        emp_salary empSalary
        from ${table_name}
    </select>

</mapper>

7、MybatisTest.java

package com.atguigu.mybatis;
import com.atguigu.mybatis.mapper.EmpMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.InputStream;
public class MybatisTest {

    SqlSessionFactory sqlSessionFactory;
    SqlSession sqlSession;
    EmpMapper empMapper;

    @BeforeEach
    public void setup() throws IOException {
        // 获取资源流,读取"mybatis-config.xml"文件
        InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        // 使用资源流创建SqlSessionFactory
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        // 使用SqlSessionFactory打开一个Session
        sqlSession = sqlSessionFactory.openSession();
        // 使用Session获取EmpMapper的Mapper对象
        empMapper = sqlSession.getMapper(EmpMapper.class);
    }

    // 在每个测试用例之后执行的清理方法
    @AfterEach
    public void teardown() {
        sqlSession.close();  // 关闭SqlSession
    }
    
    @Test
    public void getEmployeeListTest() {
        empMapper.getEmployeeList().forEach(System.out::println);
    }
    //Employee(empId=1, empName=tom, empSalary=200.33)
    //Employee(empId=2, empName=jerry, empSalary=666.66)
    //Employee(empId=3, empName=andy, empSalary=777.77)

    @Test
    public void getEmployeeByIdTest() throws IOException {
        System.out.println(empMapper.getEmployeeById(1));
        //select emp_id empId, emp_name empName, emp_salary empSalary from t_emp where emp_id = ?
    }

    @Test
    public void getEmployeeByIdTest2() throws IOException {
        System.out.println(empMapper.getEmployeeById2(1));
        //select emp_id empId, emp_name empName, emp_salary empSalary from t_emp where emp_id = 1
    }

    @Test
    public void getEmployeeListByNameTest() throws IOException {
        System.out.println(empMapper.getEmployeeListByName("lina"));
        //select emp_id empId, emp_name empName, emp_salary empSalary from t_emp where emp_name like ?
    }

    @Test
    public void getEmployeeListByNameTest2() throws IOException {
        System.out.println(empMapper.getEmployeeListByName2("lina"));
        //select emp_id empId, emp_name empName, emp_salary empSalary from t_emp where emp_name like lina
    }

    @Test
    public void getEmployeeListByNameTest3() throws IOException {
        System.out.println(empMapper.getEmployeeListByName3("lina"));
        //select emp_id empId, emp_name empName, emp_salary empSalary from t_emp where emp_name like 'lina'
    }

    @Test
    public void getEmployeeListByNameTest4() throws IOException {
        System.out.println(empMapper.getEmployeeListByName3("lina 'or 1=1 or emp_name like ' "));
        //select emp_id empId, emp_name empName, emp_salary empSalary from t_emp where emp_name like 'lina 'or 1=1 or emp_name like ' '
    }

    @Test
    public void getEmployeeList2Test() throws IOException {
        System.out.println(empMapper.getEmployeeList2("t_emp"));
        //Preparing: select emp_id empId, emp_name empName, emp_salary empSalary from t_emp
    }
}

 

 8、总结

  • #{}   相当于  之前的占位符  ”?“         PreparedStatement:执行预处理SQL命令
  • ${}   是拼接                                          Statement:执行SQL命令,注入式漏洞       " lina '  or 1=1  or  emp_name like ' " 
  • https://blog.csdn.net/m0_65152767/article/details/134057420

9、${} 的使用场景

在MyBatis中,${}形式传参的主要使用场景是当参数值是已知且不会改变的时候。这通常用于静态值,例如 数据库表名列名 等。

例如,假设你有一个用户表,表名为user_${id},其中id是一个动态参数。在MyBatis的SQL语句中,你可以使用${}来引用这个表名。当你执行这个SQL语句时,MyBatis会将${}替换为实际的参数值。

<select id="selectUserById" resultType="User">  
  SELECT * FROM user_${id} WHERE id = #{id}  
</select>

在这个例子中,user_${id}会被替换为实际的表名,例如user_1user_2等。

然而,需要注意的是,由于${}形式的参数会被直接替换到SQL语句中,因此它可能会引起SQL注入的问题。因此,当你使用这种形式的参数时,必须确保参数值是安全的,特别是当参数值来自于用户输入或其他不可信的源时。在这种情况下,应该使用其他形式的参数替换或者进行适当的输入验证和清理。在这个例子中,${tableName}会被替换为实际的表名,这个表名是根据程序运行时的某个参数动态决定的。

在MyBatis中,${}形式传参的主要使用场景包括:

  1. 直接传递数据库字段名或者表名:在SQL语句中,你可能需要引用数据库的字段名或者表名。如果这些名称是动态的,或者是根据其他参数来变化的,那么就可以使用${}来进行传递。

例如:

SELECT * FROM ${tableName} WHERE id = #{id}

在这个例子中,${tableName}会被替换为实际的表名,这个表名是根据程序运行时的某个参数动态决定的。

  1. 动态SQL语句:在构建SQL语句时,可能需要根据一些条件来动态的生成SQL语句。在这些情况下,可以使用${}来插入动态的SQL片段。

例如:

<if test="searchParam != null">  
    AND ${searchParam}  
</if>

在这个例子中,${searchParam}会被替换为实际的搜索参数,这个参数的值是在运行时决定的。

然而需要注意的是,使用${}进行传参时需要特别小心,因为它可能会导致SQL注入的问题。你必须确保所有的参数都是安全的,不能由外部用户直接控制。如果可能的话,最好使用#{}来进行传参,因为MyBatis会对#{}内的参数进行预编译和转义,从而防止SQL注入。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1268125.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

除了Whimsical,这4款在线协作软件也值得推荐!干货建议收藏。

Whimsical介绍 Whimsical是一款流行的在线协作工具&#xff0c;旨在帮助团队成员更好地进行头脑风暴、设计和规划工作。它提供了多种工具&#xff0c;包括流程图、线框图、思维导图和便签板&#xff0c;以满足团队在不同阶段的需求。Whimsical的界面简洁直观&#xff0c;易于使…

Windows核心编程 注册表

目录 注册表概述 打开关闭注册表 创建删除子健 查询写入删除键值 子健和键值的枚举 常用注册表操作 注册表概述 注册表是Windows操作系统、硬件设备以及客户应用程序得以正常运行和保存设置的核心"数据库"&#xff0c;也可以说是一个非常巨大的树状分层结构的…

浅学指针(3)

系列文章目录 文章目录 系列文章目录前言系列文章目录前言1. 字符指针变量2. 数组指针变量那数组指针变量应该是&#xff1a;存放的应该是数组的地址&#xff0c;能够指向数组的指针变量。2.2 数组指针变量怎么初始化总结&#xff1a;函数名就是地址&#xff0c;&函数名和直…

YOLOv8改进 | 2023 | DWRSeg扩张式残差助力小目标检测 (附修改后的C2f+Bottleneck)

论文地址&#xff1a;官方论文地址 代码地址&#xff1a;该代码目前还未开源&#xff0c;我根据论文内容进行了复现内容在文章末尾。 一、本文介绍 本文内容给大家带来的DWRSeg中的DWR模块来改进YOLOv8中的C2f和Bottleneck模块&#xff0c;主要针对的是小目标检测&#xff0c…

深圳市东星制冷机电受邀莅临2024国际生物发酵展,济南与您相约

深圳市东星制冷机电有限公司受邀莅临2024国际生物发酵展&#xff0c;济南3月5-7日与您相约&#xff01; 展位号&#xff1a;1号馆A53 深圳市东星制冷机电有限公司&#xff0c;&#xff08;东星集团&#xff09;是一家专业生产制冷设备的外商独资大型集团企业,拥有30多年的生产…

虚拟机安装centos7系统后网络配置

一.桥接网络和nat网络的区别1&#xff0c;桥接模式&#xff08;如果外部访问虚拟机&#xff0c;最好选这个&#xff09; 通过使用物理机网卡 具有单独ip,但是需要手动配置。 在bridged模式下&#xff0c;VMWare虚拟出来的操作系统就像是局域网中的一台独立的主机&#xff0c;它…

react-route-dom 实现简单的嵌套路由

最终效果 点击 to test1 点击to test2 > to test21 点击to test2 > to test22 代码如下 path: "page",element: <父组件 />,children: [{ path: "test1", element: <Test1 /> },{path: "test2",element: <Test2 />…

软件测试测试文档的编写和阅读

在软件测试中的流程中&#xff0c;测试文档也是一个重要的流程&#xff0c;所以测试人员也需要学习测试文档的编写和阅读。 一、定义&#xff1a; 测试文档&#xff08;Testing Documentation&#xff09;记录和描述了整个测试流程&#xff0c;它是整个测试活动中非常重要的文…

BIO、NIO、selector、Netty代码Demo示例

文章目录 &#xff08;一&#xff09;BIO&#xff08;Blocking I/O 阻塞I/O&#xff09;&#xff08;二&#xff09;NIO&#xff08;Non-Blocking I/O 非阻塞I/O&#xff09;&#xff08;三&#xff09;IO多路复用--Selector&#xff08;四&#xff09;Netty &#xff08;一&am…

翻译求职简历,如何做效果好?

随着国内经济的蓬勃发展&#xff0c;众多求职者都渴望能在外企寻得一席之地。而一份精彩绝伦的外文简历&#xff0c;往往能瞬间提高求职者的成功率。但如何才能做好这份简历翻译呢&#xff1f; 其实&#xff0c;简历翻译绝非简单的中英文对照。不同国家有着各自独特的语言表达方…

【海思SS528 | VDEC】MPP媒体处理软件V5.0 | VDEC的使用总结

&#x1f601;博客主页&#x1f601;&#xff1a;&#x1f680;https://blog.csdn.net/wkd_007&#x1f680; &#x1f911;博客内容&#x1f911;&#xff1a;&#x1f36d;嵌入式开发、Linux、C语言、C、数据结构、音视频&#x1f36d; &#x1f923;本文内容&#x1f923;&a…

操作系统 day14(进程同步、进程互斥、互斥的代码实现、互斥的硬件实现、互斥锁)

进程同步 概念 进程的异步性体现在&#xff0c;例如&#xff1a;当有I/O操作时&#xff0c;进程需要等待I/O操作&#xff0c;而每个I/O操作又是不同的&#xff0c;所以进程没有一个固定的顺序&#xff0c;固定的时间来执行&#xff0c;而这体现了进程的异步性。 进程互斥 …

【Java】泛型的简单使用

文章目录 一、包装类1.基本数据类型和对应的包装类2.自动装箱和自动拆箱3.手动装箱和手动拆箱 二、什么是泛型三、泛型的使用四、裸类型&#xff08;Raw Type&#xff09;五、泛型是如何编译的六、泛型的上界七、泛型方法总结 一、包装类 在了解泛型之前我们先了解什么是包装类…

【Java学习笔记】75 - 算法优化入门 - 马踏棋盘问题

一、意义 1.算法是程序的灵魂&#xff0c;为什么有些程序可以在海量数据计算时&#xff0c;依然保持高速计算? 2.拿老韩实际工作经历来说&#xff0c;在Unix下开发服务器程序&#xff0c;功能是要支持上千万人同时在线&#xff0c;在上线前&#xff0c; 做内测&#xff0c;一…

FPGA设计时序约束十、others类约束之Set_Disable_Timing

目录 一、序言 二、Set Disable Timing 2.1 基本概念 2.2 设置界面 2.3 命令语法 2.4 命令示例 三、工程示例 四、参考资料 一、序言 在Vivado的时序约束窗口中&#xff0c;存在一类特殊的约束&#xff0c;划分在others目录下&#xff0c;可用于设置忽略或修改默认的时…

一文学会Aiohttp

一、什么是aiohttp库 aiohttp库官网&#xff1a;https://docs.aiohttp.org/en/stable/ aiohttp是一个Python的HTTP客户端/服务器框架&#xff0c;它基于asyncio库实现异步编程模型&#xff0c;可以支持高性能和高并发的HTTP通信。aiohttp用于编写异步的Web服务器、Web应用程序…

【hacker送书第5期】SQL Server从入门到精通(第5版)

第5期图书推荐 内容简介作者简介图书目录参与方式 内容简介 SQL Server从入门到精通&#xff08;第5版&#xff09;》从初学者角度出发&#xff0c;通过通俗易懂的语言、丰富多彩的实例&#xff0c;详细介绍了SQL Server开发所必需的各方面技术。全书分为4篇共19章&#xff0c;…

Linux下文件操作函数

一.常见IO函数 fopen fclose fread fwrite fseek fflush fopen 运行过程 &#xff1a;打开文件 写入数据 数据写到缓冲区 关闭文件后 将数据刷新入磁盘 1.fopen 返回文件类型的结构体的指针 包括三部分 1).文件描述符&#xff08;整形值 索引到磁盘文件&#xff09;…

【重磅合作】九章云极DataCanvas公司与生态伙伴强强联手,构建人工智能强生态!

11月21日&#xff0c;在「筑基赋能 智向未来」九章云极DataCanvas大模型系列成果发布会上&#xff0c;九章云极DataCanvas公司与人工智能产业链上下游合作伙伴广东民营投资股份有限公司&#xff08;以下简称“粤民投”&#xff09;、西藏赛富合银投资有限公司&#xff08;以下简…

网络入门---网络编程预备知识

目录标题 ifconfigip地址和mac地址的区别端口号pid和端口号UDP和TCP的初步了解网络字节序socket套接字 ifconfig 通过指令ifconfig便可以查看到两个网络接口&#xff1a; 我们当前使用的是一个linux服务器并是一个终端设备&#xff0c;所以他只需要一个接口用来入网即可&…