SteelReed

Search

Search posts, questions…

JPA & HibernateQuestion 22 / 24

Junior

Write MyBatis SQL with annotations or XML? How do dynamic SQL tags <if>, <foreach>, <choose>, <sql> work, and how does #{} differ from ${}?

Short answer

Annotations (@Select) fit short, fixed statements; dynamic SQL (optional conditions) belongs in XML with <where>, <if>, <foreach>. Most important: #{} passes parameters safely, ${} pastes the string straight in and invites SQL injection.

short, fixedoptional conditionsa valuea column nameWhat kind of SQL?annotation @SelectXML: where, if, foreachWhat goes into SQL?bind a parameter: safepaste a string: whitelist only

3 points to say:

  1. Every value uses #{}.
  2. ${} only for column names checked against a whitelist.
  3. <choose> picks exactly one branch; several <if>s pick every true one.

Keep reading the deep dive

Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.