The case · 03

Why MyBatis

This is the contrarian choice in the stack, so it needs the strongest argument. Here it is: the database is the part of your system most likely to become the bottleneck, and MyBatis is the only option that keeps it fully under your control without making you write JDBC.

⏱ 13 min readOpinion, with evidence

1 · The SQL is visible, reviewable and version-controlled

MyBatis

You know what runs

<select id="findOverdue" resultMap="orderMap">
  SELECT o.order_id, o.reference, o.total_amount
  FROM customer_order o
  WHERE o.status = 'PLACED'
    AND o.placed_at &lt; now() - interval '48 hours'
  ORDER BY o.placed_at
  LIMIT #{limit}
</select>
Generating ORM

You know what you asked for

List<Order> findByStatusAndPlacedAtBefore(
    OrderStatus status, Instant cutoff, Pageable page);

// The SQL is produced at runtime by a
// dialect, a fetch plan and a mapping —
// none of which are in your repository.

A DBA can review a MyBatis mapper without knowing Java. A slow query appears in pg_stat_statements in a form you can search your codebase for. Neither is true of generated SQL.

2 · Performance is a decision, not a discovery

The N+1 problem is structural, not accidental

Lazy loading means a getter can issue a query. That is a feature until an innocent order.getCustomer().getName() inside a loop turns one request into four hundred queries — usually discovered in production, because the test dataset had five rows.

In MyBatis one mapper method is one statement. There is no getter that secretly hits the database, because there is no proxy.

Failure modeORMMyBatis
N+1 from lazy loadingCommonImpossible
LazyInitializationExceptionCommonDoes not exist
Cartesian explosion from multiple fetch joinsEasy to hitYou wrote the join; you saw it
Unexpected UPDATE from dirty checkingPossibleImpossible — writes are explicit
Paging silently done in memoryYes, with collection joinsNo

3 · You can use the database you paid for

PostgreSQL's best features are exactly the ones a generating ORM cannot express naturally. With MyBatis they are simply the SQL you write:

OrderMapper.xml — ordinary MyBatis, powerful PostgreSQL
<select id="dailyRevenue" resultType="RevenuePoint">
  SELECT date_trunc('day', placed_at)          AS day,
         sum(total_amount)                     AS revenue,
         sum(sum(total_amount)) OVER (
           ORDER BY date_trunc('day', placed_at)
         )                                     AS running_total,
         rank() OVER (ORDER BY sum(total_amount) DESC) AS rank
  FROM customer_order
  WHERE placed_at &gt;= #{from}
  GROUP BY 1
  ORDER BY 1
</select>

<select id="searchMetadata" resultMap="orderMap">
  SELECT * FROM customer_order
  WHERE metadata @&gt; #{filter}::jsonb        <!-- GIN index -->
</select>

<insert id="upsertStock">
  INSERT INTO stock (product_id, quantity) VALUES (#{productId}, #{quantity})
  ON CONFLICT (product_id)
  DO UPDATE SET quantity = stock.quantity + EXCLUDED.quantity
</insert>

4 · Dynamic SQL is a solved problem

A search screen with eight optional filters is the single most common requirement in business software, and it is where ORMs are least pleasant — Criteria APIs and Specifications are verbose and hard to read.

MyBatis dynamic SQL
<select id="search" resultMap="orderMap">
  SELECT <include refid="orderColumns"/> FROM customer_order o
  <where>
    <if test="status != null">AND o.status = #{status}</if>
    <if test="from   != null">AND o.placed_at &gt;= #{from}</if>
    <if test="customerIds != null and customerIds.size() > 0">
      AND o.customer_id IN
      <foreach collection="customerIds" item="id" open="(" separator="," close=")">#{id}</foreach>
    </if>
  </where>
  ORDER BY o.placed_at DESC
  LIMIT #{limit} OFFSET #{offset}
</select>

Every value is still a bound parameter, so this is injection-safe. Full treatment in MyBatis chapter 7.

5 · Legacy schemas stop being an obstacle

Columns called USR_FLG_1, composite keys, tables shared with a mainframe, views you may not alter. An ORM wants to own the schema; MyBatis just maps whatever is there via a resultMap, leaving your domain classes clean.

Where an ORM genuinely wins

Do not choose MyBatis reflexively

If your application is CRUD over an object graph you own, Hibernate's dirty checking, cascades and schema generation save real work. MyBatis will feel like typing.

SituationBetter choice
Green-field, entity-graph CRUDSpring Data JPA
You want schema generated from codeJPA + Hibernate
Heavy aggregation and reportingMyBatis
Search screens with many filtersMyBatis
Legacy or externally owned schemaMyBatis
Bulk loads and stored proceduresMyBatis

Using both is legitimate: JPA for the transactional entity graph, MyBatis for reporting and bulk work, sharing one data source and one Spring transaction.

What it costs

  • You write the SQL. More typing up front for simple CRUD.
  • No schema generation. Bring Flyway — which you should anyway.
  • Portability is manual. Vendor-specific SQL means committing to a database. Given that database is PostgreSQL, this is an easy commitment.
  • Refactoring is weaker. Renaming a column means grepping XML; tests cover the gap.

What is the strongest argument for MyBatis in a long-lived application?

MyBatis is not faster than JDBC — it is JDBC, with the boilerplate removed. It also requires more code than an ORM for simple CRUD. What it buys is that one mapper method equals one statement, so there is no hidden query behaviour to discover later.