MyBatis: Difference between # and *
MyBatis: Difference between #
and *
In MyBatis, both #
and *
are used in SQL queries, but they serve different purposes:
#
- Parameter Placeholder
The #
symbol is used to represent parameter placeholders in SQL queries. It is used for parameter substitution and ensures that user input is safely injected into the query to avoid SQL injection. MyBatis automatically escapes special characters in parameters when #
is used.
Example:
<select id="findUserById" parameterType="int" resultType="User">
SELECT * FROM users WHERE id = #{userId}
</select>
In this example, #{userId}
will be replaced with the value of userId
from the Java code, and MyBatis will handle any necessary escaping.
*
- Wildcard (for result mapping)
The *
symbol in MyBatis is typically used in a result map or select clause to indicate selecting all columns or when dynamically mapping results to properties. It doesn't have a special function within MyBatis itself, but it is often used in SQL statements as part of selecting all columns in a table.
Example:
<select id="selectAllUsers" resultType="User">
SELECT * FROM users
</select>
In this query, * selects all columns from the users table.