Parameters: #{}, ${} and @Param

Harry · 11 Sep 2026 · 8 views

The Two Parameter Styles

MyBatis offers two ways to substitute values into SQL, and they are not interchangeable.

#{user}: Safe PreparedStatement Binding

SELECT * FROM customers WHERE email = #{email}

#{} becomes a ? placeholder. The driver escapes and binds the value, which prevents SQL injection. You should almost always use #{}.

${user}: Direct String Substitution

SELECT * FROM customers ORDER BY ${orderBy}

${} pastes the raw string into the SQL. It is needed for identifiers such as column names or ORDER BY clauses, which cannot be bound as parameters. Never use ${} with user-supplied input without strict validation.

Passing Several Parameters

List<Customer> search(@Param("name") String name,
                    @Param("city") String city,
                    @Param("limit") int limit);
<select id="search" resultType="Customer">
  SELECT * FROM customers
  WHERE name LIKE #{name} AND city = #{city}
  LIMIT #{limit}
</select>

Key Points

  • #{} binds values via PreparedStatement and blocks injection.
  • ${} substitutes raw text for identifiers only.
  • @Param gives XML references deterministic names.
  • Default to #{}; reach for ${} only for identifiers.
Share this post:

Comments (0)

Please login or register to comment.