Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

Write a MyBatis mapper interface in Spring Boot that selects orders by customer id with an optional status filter, mapping snake_case columns to a Java record. Explain #{} versus ${}.

We declare an @Mapper interface with a find(customerId, status) method, write the SQL in XML or an annotation script with <where><if test="status != null"> so the status condition appears only when a status is given, and map snake_case columns to the record either with map-underscore-to-camel-case=true or a resultMap. #{} becomes a PreparedStatement parameter, which is safe from SQL injection, while ${} pastes text straight into the SQL, which we only use for identifiers such as a sort column, and only after checking them against a whitelist.

Background to this question

MyBatis is the choice of many teams that want to write their own SQL but not their own JDBC plumbing: it maps query results to objects and builds dynamic SQL from small templates. The two things every MyBatis developer must get right are the mapping from columns to Java types and the difference between #{} and ${}, because the second one is a common cause of SQL injection. In this answer, we will recap how MyBatis works with Spring Boot, write the mapper in XML and with annotations, map the columns to a record, and then look closely at #{} versus ${}.

1A Quick Recap of MyBatis in Spring Boot

MyBatis is a SQL mapper. We write the SQL ourselves, and MyBatis does three things: it binds our method parameters into the statement, it runs it through JDBC, and it maps each result row to an object. Unlike JPA, it does not track entities, generate SQL or manage a persistence context; what we write is what runs.

With mybatis-spring-boot-starter on the classpath, Boot creates a SqlSessionFactory from our DataSource, scans for interfaces annotated with @Mapper and turns each into a Spring bean that we can inject. Calls through a mapper join Spring's transactions, so a @Transactional service method can call several mappers on the same connection.

YAML
# application.yml
mybatis:
mapper-locations: classpath:mappers/*.xml
configuration:
map-underscore-to-camel-case: true # customer_id -> customerId

2The Mapper Interface and Record

The mapper is a plain interface. @Param gives each parameter the name we use inside the SQL. The result type is a Java record whose components match the columns after camel-case conversion.

Java
public record Order(long id, long customerId, String status, BigDecimal totalAmount, Instant createdAt) {}
@Mapper
public interface OrderMapper {
List<Order> find(@Param("customerId") long customerId, @Param("status") String status);
}

Records have no setters and no no-argument constructor, so MyBatis must create them through the constructor. By default it matches columns to constructor arguments in order, so the SELECT list must follow the record's component order. Newer MyBatis 3.5 releases can also match by argument name, with the arg-name-based-constructor-auto-mapping setting and the -parameters compiler flag. Support has changed across versions, so check your MyBatis version, or use an explicit resultMap with a constructor element to remove all doubt.

3Writing the Dynamic SQL in XML

The XML mapper's namespace is the interface's full name, and the statement id is the method name. The <where> element adds WHERE only if at least one condition inside it produces text, and removes a leading AND or OR. The <if> element includes its body only when its test is true.

XML
<mapper namespace="com.example.orders.OrderMapper">
<select id="find" resultType="com.example.orders.Order">
SELECT id, customer_id, status, total_amount, created_at
FROM orders
<where>
customer_id = #{customerId}
<if test="status != null">AND status = #{status}</if>
</where>
ORDER BY created_at DESC
</select>
</mapper>
// find(42, null)
// SELECT ... FROM orders WHERE customer_id = ? ORDER BY created_at DESC -- params: 42
// find(42, "SHIPPED")
// SELECT ... WHERE customer_id = ? AND status = ? ORDER BY created_at DESC -- params: 42, SHIPPED

Notice that both versions use question marks. The values travel separately as parameters, which is the safe behaviour we will come back to. Here customer_id is always present, so <where> is not strictly needed, but it keeps the template correct if that condition later becomes optional too.

4The Same Mapper With Annotations

For a short query, we can skip the XML file and write the SQL on the method. Dynamic tags still work if we wrap the SQL in a <script> element.

Java
@Mapper
public interface OrderMapper {
@Select("""
<script>
SELECT id, customer_id, status, total_amount, created_at
FROM orders
<where>
customer_id = #{customerId}
<if test="status != null">AND status = #{status}</if>
</where>
ORDER BY created_at DESC
</script>
""")
List<Order> find(@Param("customerId") long customerId, @Param("status") String status);
}

Annotations are convenient for small mappers; XML is easier to read once statements grow or share fragments. Teams usually choose one style per project.

5#{} Versus ${}

This is the most important detail in MyBatis. #{status} tells MyBatis to put a ? placeholder in the SQL and bind the value through PreparedStatement.setString(). The database receives the SQL text and the value separately, so the value can never change the structure of the statement, whatever characters it contains.

${status} is plain text substitution. MyBatis pastes the value into the SQL string before sending it. If the value comes from a user, the user can write SQL.

XML
<!-- Broken: value substituted as text -->
AND status = '${status}'
// find(42, "x' OR '1'='1")
// SELECT ... WHERE customer_id = 42 AND status = 'x' OR '1'='1' -- every customer's orders
<!-- Safe: value bound as a parameter -->
AND status = #{status}
// SELECT ... WHERE customer_id = ? AND status = ? -- params: 42, x' OR '1'='1 (no match)
#{} and ${} side by side
#{value}${value}
What MyBatis doesPuts ? in the SQL and binds the valuePastes the text into the SQL
SQL injectionNot possible through the valuePossible if the text comes from input
Use forAll values: ids, statuses, datesIdentifiers only: sort column, direction
RuleThe default for everythingOnly after a whitelist in Java

So why does ${} exist at all? Because placeholders can only stand for values, never for identifiers or keywords. We cannot write ORDER BY ? and bind a column name. For a user-chosen sort column, ${} is the only way, and it is safe only if the text can never come from the user directly. We map the user's choice to a fixed set of allowed columns in Java first.

6A Safe Sort Column

Here is the whitelist pattern for sorting. The controller accepts a sort name from the user, but the mapper only ever receives one of our own column names.

Java
enum OrderSort {
NEWEST("created_at DESC"), TOTAL("total_amount DESC");
final String sql;
OrderSort(String sql) { this.sql = sql; }
}
List<Order> findSorted(@Param("customerId") long customerId, @Param("orderBy") String orderBy);
// <select id="findSorted" ...> ... ORDER BY ${orderBy} </select>
mapper.findSorted(42, OrderSort.valueOf(userInput).sql); // "total_amount DESC" or an exception

Notice that OrderSort.valueOf() throws for anything that is not a known constant, so an attacker's text never reaches the SQL. The ${} is now safe because the set of possible values is ours.

7Follow-up questions

How does MyBatis differ from JPA in what it does with the returned objects?

MyBatis returns plain objects and forgets them. Changing an Order after loading it does nothing to the database; we must call an update statement ourselves. JPA keeps loaded entities managed in a persistence context and writes changes at flush through dirty checking. MyBatis is simpler and more predictable, at the cost of writing every statement.

What is the difference between map-underscore-to-camel-case and a resultMap?

The setting is a global rule that turns customer_id into customerId for every automatic mapping, which is enough when the naming is consistent. A resultMap is an explicit mapping per statement or type, which we need for columns that do not follow the rule, for constructor mapping by name, and for nested objects and collections built from joins.

Does #{} work inside LIKE patterns?

Yes, but the wildcards must be part of the value or concatenated in SQL, not pasted with ${}. We can pass '%' + term + '%' as the parameter, or write status LIKE CONCAT('%', #{term}, '%'), or use a <bind> element to build the pattern. Each keeps the user's text as a bound value.

8Conclusion

In this answer, we wrote a MyBatis mapper for orders with an optional status filter. The starter scans the @Mapper interface and joins Spring transactions, the <where> and <if> tags add the status condition only when a status is given, and map-underscore-to-camel-case or a resultMap maps snake_case columns to a record, created through its constructor. We saw that #{} binds values as PreparedStatement parameters and is safe, while ${} pastes text into the SQL and is only for identifiers chosen from a whitelist, and that MyBatis maps SQL we write rather than tracking entity state like JPA.

What to say in the interviewAbout 90 seconds aloud

Open with

I would write an @Mapper interface, OrderMapper, with a method find that takes a long customerId and a String status, each with @Param so the names are available in the SQL.

Then, if they want more

The SQL lives in an XML mapper with the interface's full name as namespace, or in an @Select with a script element. It selects the columns from orders, and inside a where element it always has customer_id equals #{customerId}, plus an if element with test status not null that adds AND status equals #{status}. So passing null drops the filter.

For the snake_case columns, I enable map-underscore-to-camel-case in the MyBatis configuration, or write a resultMap. Because the target is a record, MyBatis builds it through the constructor, so the column order has to match the components, or I use a constructor resultMap; name-based constructor mapping depends on the MyBatis version. The starter scans @Mapper interfaces and joins Spring transactions.

The key difference between the two placeholders: #{} becomes a question mark and the value is bound on a PreparedStatement, so it cannot inject SQL. ${} pastes raw text into the statement, which is needed for identifiers like a sort column, since you cannot bind a column name, and it is only safe if I map the user's choice to a fixed whitelist, for example an enum, before passing it.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
java.sql, package documentation
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Write a MyBatis mapper interface in Spring Boot that selects orders by customer id with...": https://scrivio-interview-library.netlify.app/databases/jdbc/f0e24684f0/