FAQ and interview questions
Forty questions, ordered roughly from fundamentals to internals. Useful as a revision pass after the course, and as interview preparation on either side of the table.
Fundamentals
1 · What is MyBatis?
A persistence framework that maps SQL statements to Java interface methods and result sets to objects. You write the SQL; MyBatis handles parameter binding, result mapping, statement caching and resource management.
2 · Is MyBatis an ORM?
Not in the Hibernate sense. It is a SQL mapper. There is no persistence context, no dirty checking, no cascading and no schema generation. It maps statements and results, nothing more.
3 · How does MyBatis differ from Hibernate?
Hibernate generates SQL from an entity model and manages object state. MyBatis executes the SQL you wrote. Hibernate wins on green-field CRUD-heavy domains; MyBatis wins on legacy schemas, report-heavy workloads and anything where the SQL itself is the value.
4 · What replaced iBATIS?
MyBatis is iBATIS renamed and rewritten in 2010. SqlMapClient became
SqlSession, and mapper interfaces plus dynamic SQL via OGNL arrived in 3.x.
5 · What are the core objects and their scopes?
SqlSessionFactoryBuilder (method scope), SqlSessionFactory
(application scope, thread-safe), SqlSession (request scope, not
thread-safe), mapper (method scope, tied to its session).
6 · Do mapper interfaces need an implementation class?
No. MyBatis creates a JDK dynamic proxy. MapperProxy intercepts the call,
resolves namespace + "." + methodName to a MappedStatement, and
delegates to the session.
Mapping
7 · What is the difference between #{} and ${}?
#{} becomes a JDBC ? placeholder — safe, type-handled, cannot alter
the statement structure. ${} is raw string substitution — injectable, and only
acceptable for identifiers taken from a whitelist.
8 · resultType or resultMap?
resultType for flat results whose columns match properties.
resultMap when you need explicit column mapping, nested objects, custom type
handlers, constructor mapping or a discriminator. They are mutually exclusive on one
statement.
9 · How do I map user_name to userName?
Set mapUnderscoreToCamelCase=true, or alias the column
(SELECT user_name AS userName), or declare it in a resultMap.
10 · What does <id> do in a result map?
Marks the identity column. MyBatis uses it to recognise repeated parent rows in a join and collapse them into one object, and as part of the internal object cache key. Omit it in a one-to-many and you get one parent per row.
11 · association versus collection?
association is has-one, collection is has-many. Collection takes
ofType (the element type); association takes javaType.
12 · Nested results or nested select?
Nested results = one join, one query, no lazy loading. Nested select = one extra query per parent row, lazy-loadable. Use nested results for anything that returns a list.
13 · What is the N+1 problem in MyBatis?
A list query plus a nested select fires one query for the list and one per row. Fix it
with a join and a nested <collection>, and prevent regressions with a test
that asserts the statement count.
14 · Can one mapper use both XML and annotations?
Yes, as long as no statement id is defined in both places. Duplicates fail at startup with “Mapped Statements collection already contains value for …”.
15 · What is a TypeHandler?
A bidirectional converter between a Java type and a JDBC type. Built-ins cover primitives,
String, BigDecimal, java.time, arrays, blobs and
name-based enums. Extend BaseTypeHandler<T> for anything else — code-backed
enums, JSON columns, encrypted fields.
16 · How do I map an immutable class or record?
Use <constructor> with <idArg> and <arg>.
Argument order must match the constructor, unless you supply name attributes
and compile with -parameters.
Dynamic SQL
17 · Which dynamic SQL tags exist?
if, choose/when/otherwise,
where, set, trim, foreach,
bind, plus sql/include for reuse.
18 · What exactly does <where> do?
Emits the WHERE keyword only if the body produced content, and strips one
leading AND or OR. It does not remove trailing connectors.
19 · What does <set> do?
Emits SET and removes the trailing comma. Keep one unconditional assignment
so the clause is never empty.
20 · How do I write an IN clause?
<foreach collection="ids" item="id" open="(" separator="," close=")">#{id}</foreach>.
Guard against an empty list in Java and chunk large ones.
21 · What is the collection attribute for a plain List
parameter?
list (or collection); an array is array. With
@Param("ids") it is ids — which is what you should always use.
22 · Why does test="code == 'Y'" not work?
OGNL reads 'Y' as a char, and a String never equals a
char. Write "Y".equals(code) or code == "Y".toString().
23 · What is <bind> for?
Creating a local variable from an OGNL expression — most often a LIKE pattern
('%' + name + '%') so you avoid vendor-specific string concatenation in SQL.
24 · How do I see the generated SQL?
Set the mapper package logger to DEBUG, or fetch it programmatically with
configuration.getMappedStatement(id).getBoundSql(param).getSql().
Runtime, caching, transactions
25 · Describe the two cache levels.
L1 is per SqlSession, always on, cleared by any write, commit, rollback or
close. L2 is per mapper namespace, shared across sessions, opt-in via
<cache/>, and populated only on commit.
26 · What makes up a cache key?
Statement id, RowBounds, the final SQL text, all parameter values, and the
environment id.
27 · When is L2 a bad idea?
Multiple application instances, external writers, write-heavy tables, very large result objects, or highly parameterised queries. Read-mostly reference data is the good case.
28 · What is cache-ref?
Makes one namespace share another's cache, so writes in either namespace invalidate the shared entries. Necessary when two mappers touch the same table.
29 · What are the executor types?
SIMPLE (new statement each call), REUSE (caches prepared
statements per session), BATCH (queues updates until flush).
30 · What does an insert return in BATCH mode?
Statement.SUCCESS_NO_INFO (-2147482646). Real counts come from
flushStatements() as a list of BatchResult.
31 · Does openSession() autocommit?
No. Use openSession(true) for autocommit, otherwise call
commit(). close() rolls back anything uncommitted.
32 · How do I get the generated primary key?
useGeneratedKeys="true" keyProperty="id" for identity columns, or
<selectKey order="BEFORE"> for sequences. Either way the value is written
onto the parameter object; the method's return value is the row count.
33 · How is optimistic locking implemented?
A version column, SET version = version + 1 and
WHERE id = #{id} AND version = #{version}. A zero row count means someone else
won.
Spring and operations
34 · What does the Spring Boot starter configure?
A SqlSessionFactory over the Spring DataSource, a thread-safe
SqlSessionTemplate, mapper proxy beans for @Mapper interfaces, and
SpringManagedTransactionFactory so MyBatis joins the Spring transaction.
35 · @Mapper or @MapperScan?
@Mapper per interface is explicit and works when the interfaces are inside the
component scan. @MapperScan is needed for packages outside it, or for library
modules.
36 · Should I call commit() under Spring?
No. @Transactional owns the boundary. Calling commit on a Spring-managed
session throws UnsupportedOperationException or silently breaks the
transaction semantics.
37 · How do I run batch operations under Spring?
Define a second SqlSessionTemplate with ExecutorType.BATCH and get
mappers from it, flushing periodically.
38 · What causes Invalid bound statement (not found)?
XML not on the runtime classpath, namespace not matching the interface FQN, statement id
not matching the method name, or two mappers sharing a namespace. Check
target/classes first.
39 · What is a MyBatis plugin?
An Interceptor that proxies Executor,
ParameterHandler, ResultSetHandler or StatementHandler.
Used for pagination, timing, tenant filters, encryption and audit columns.
40 · How should mappers be tested?
Against a real database — H2 for speed, Testcontainers for anything vendor-specific. Mocking a mapper tests nothing, because the mapper contains no logic.
One-page cheat sheet
Statement attributes
<select id resultType|resultMap
useCache flushCache timeout
fetchSize statementType/>
<insert id useGeneratedKeys
keyProperty keyColumn/>
<update id flushCache/>
<delete id flushCache/>
Dynamic tags
<if test="...">
<choose><when><otherwise>
<where> <set>
<trim prefix prefixOverrides
suffix suffixOverrides>
<foreach collection item index
open separator close>
<bind name value>
Result map elements
<id> <result>
<constructor><idArg><arg>
<association javaType|resultMap
columnPrefix select fetchType>
<collection ofType ...>
<discriminator><case>
Settings you will actually change
mapUnderscoreToCamelCase = true cacheEnabled = false defaultStatementTimeout = 30 defaultFetchSize = 200 callSettersOnNulls = true localCacheScope = SESSION defaultExecutorType = SIMPLE autoMappingUnknownColumnBehavior = WARNING
Fifteen chapters, from pom.xml to interceptors. If something here was unclear
or you hit a case we did not cover, tell us — reader
questions are where the next chapters come from.