mybatis基础(2)
配置式使用mybatis,可以三步走:
- 读取配置文件,即mybatis-config.xml
- 通过配置文件来创建SqlSessionFactory
- 新建SqlSession来执行sql
mybatis 提供了注解和XML两种方式来连接接口方法和sql语句
如果单独使用mybatis ,那么mapper接口必须和.xml配置文件在同一个包中,但是如果使用spring等工具可以不必接收此限制
参数符号
若以#{}作为参数符号,MyBatis则会创建一个预处理语句(PreparedStatement),它会被处理成 ?。如果你不希望使用预处理,那么可以使用${}参数符号,MyBatis 会以字符串的形式进行拼接
In MyBatis, #{}
and ${}
are two different syntaxes used in SQL statements, and they serve different purposes:
-
#{}
(Parameter Substitution):-
#{}
is used for parameter substitution in prepared statements. It helps prevent SQL injection by automatically handling escaping and quoting of parameters. -
MyBatis treats values placed inside
#{}
as bind parameters and automatically applies proper escaping and formatting based on the parameter type. -
Example:
xml<!-- Using #{parameter} for parameter substitution --> SELECT * FROM users WHERE id = #{userId}
-
In Java code, you would then provide the actual value for
userId
when executing the SQL statement.
-
-
${}
(String Substitution):-
${}
is used for string substitution in SQL statements. It directly replaces the variable or expression with its string representation. -
Unlike
#{}
,${}
does not provide protection against SQL injection because it directly inserts the value into the SQL string without any formatting. -
Example:
xml<!-- Using ${parameter} for string substitution --> SELECT * FROM users WHERE id = ${userId}
-
In this case, the value of
userId
will be directly inserted into the SQL string as a string.
-
Key Differences:
-
Security:
#{}
is more secure against SQL injection because it handles parameter formatting.${}
is less secure since it directly inserts the string representation of the variable.
-
Prepared Statements:
#{}
is typically used in prepared statements, where MyBatis handles parameter formatting.${}
is used for string interpolation and is suitable when you want to directly insert a string representation.
-
Data Types:
#{}
is aware of the data type of the parameter and applies appropriate formatting.${}
does not consider the data type and directly inserts the string representation.
-
Quoting and Escaping:
#{}
automatically quotes and escapes values, making it suitable for most scenarios.${}
does not quote or escape values, so it's important to ensure that values are properly formatted before using${}
to prevent SQL errors.
In general, it's recommended to use #{}
for most cases, especially when dealing with user input or dynamic values, to prevent SQL injection. Use ${}
when you need to directly substitute a string and are certain about the safety of the value being inserted.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)