Chapter 02

The MyBatis persistence layer

Now the schema pays off. Every mapper below is a direct expression of a query the application actually needs — no lazy loading, no proxies, no surprise N+1.

⏱ 20 min readLevel: intermediateHands-on

Domain types

order/Order.java
public class Order {
    private Long id;
    private Long customerId;
    private String reference;
    private OrderStatus status;
    private BigDecimal totalAmount;
    private String currency;
    private Map<String, Object> metadata = new LinkedHashMap<>();
    private int version;
    private OffsetDateTime placedAt;
    private List<OrderLine> lines = new ArrayList<>();
    // getters and setters
}

public record OrderLine(Long id, Long productId, String sku, String productName,
                        int quantity, BigDecimal unitPrice, BigDecimal lineTotal) {}

public enum OrderStatus { DRAFT, PLACED, PAID, FULFILLED, DELIVERED, CANCELLED, REFUNDED }
Why Order is a class and OrderLine a record

MyBatis populates a collection result map by calling setters on a mutable parent while it accumulates children. Records are perfect for the immutable leaves, and constructor result maps handle them.

The mapper interface

order/OrderMapper.java
@Mapper
public interface OrderMapper {

    Optional<Order> findById(@Param("id") long id);

    List<OrderSummary> search(@Param("q") OrderSearchQuery query);

    long countMatching(@Param("q") OrderSearchQuery query);

    void insert(Order order);                       // fills order.id via useGeneratedKeys

    void insertLines(@Param("orderId") long orderId,
                     @Param("lines") List<OrderLine> lines);

    int updateStatus(@Param("id") long id,
                     @Param("to") OrderStatus to,
                     @Param("expectedVersion") int expectedVersion);

    int updateTotal(@Param("id") long id, @Param("total") BigDecimal total);

    void deleteLines(@Param("orderId") long orderId);

    List<OrderEvent> findEvents(@Param("orderId") long orderId);

    void insertEvent(OrderEvent event);
}

Loading the aggregate in one query

resources/com/bitsnippets/oms/order/OrderMapper.xml
<mapper namespace="com.bitsnippets.oms.order.OrderMapper">

  <resultMap id="orderMap" type="Order">
    <id     property="id"          column="order_id"/>
    <result property="customerId"  column="customer_id"/>
    <result property="reference"   column="reference"/>
    <result property="status"      column="status"/>
    <result property="totalAmount" column="total_amount"/>
    <result property="currency"    column="currency"/>
    <result property="metadata"    column="metadata" typeHandler="JsonTypeHandler"/>
    <result property="version"     column="version"/>
    <result property="placedAt"    column="placed_at"/>

    <collection property="lines" ofType="OrderLine" columnPrefix="l_"
                javaType="java.util.List">
      <constructor>
        <idArg  column="line_id"      javaType="Long"/>
        <arg    column="product_id"   javaType="Long"/>
        <arg    column="sku"          javaType="String"/>
        <arg    column="product_name" javaType="String"/>
        <arg    column="quantity"     javaType="int"/>
        <arg    column="unit_price"   javaType="java.math.BigDecimal"/>
        <arg    column="line_total"   javaType="java.math.BigDecimal"/>
      </constructor>
    </collection>
  </resultMap>

  <select id="findById" resultMap="orderMap">
    SELECT o.order_id, o.customer_id, o.reference, o.status, o.total_amount,
           o.currency, o.metadata, o.version, o.placed_at,
           l.line_id      AS l_line_id,
           l.product_id   AS l_product_id,
           p.sku          AS l_sku,
           p.name         AS l_product_name,
           l.quantity     AS l_quantity,
           l.unit_price   AS l_unit_price,
           l.line_total   AS l_line_total
    FROM   customer_order o
    LEFT   JOIN order_line l ON l.order_id  = o.order_id
    LEFT   JOIN product    p ON p.product_id = l.product_id
    WHERE  o.order_id = #{id}
    ORDER  BY l.line_id
  </select>
</mapper>
Two details that matter

columnPrefix="l_" keeps line columns from colliding with order columns — without it, quantity from a second collection would be ambiguous. And the <id> element is what lets MyBatis fold the repeated order rows of the join back into one object with many lines. Omit it and you get one Order per line.

OrderMapper.xml — the list screen
<sql id="searchFilters">
  <where>
    <if test="q.status != null">
      AND o.status = #{q.status}::order_status
    </if>
    <if test="q.customerId != null">
      AND o.customer_id = #{q.customerId}
    </if>
    <if test="q.from != null">
      AND o.placed_at >= #{q.from}
    </if>
    <if test="q.to != null">
      AND o.placed_at < #{q.to}
    </if>
    <if test="q.minTotal != null">
      AND o.total_amount >= #{q.minTotal}
    </if>
    <if test="q.text != null and q.text != ''">
      AND (o.reference ILIKE '%' || #{q.text} || '%'
           OR c.full_name ILIKE '%' || #{q.text} || '%')
    </if>
    <if test="q.channel != null">
      AND o.metadata @> jsonb_build_object('channel', #{q.channel})
    </if>
  </where>
</sql>

<select id="search" resultType="OrderSummary">
  SELECT o.order_id     AS id,
         o.reference,
         o.status,
         o.total_amount AS totalAmount,
         o.currency,
         o.placed_at    AS placedAt,
         c.full_name    AS customerName
  FROM   customer_order o
  JOIN   customer c ON c.customer_id = o.customer_id
  <include refid="searchFilters"/>
  ORDER BY o.placed_at DESC, o.order_id DESC
  LIMIT #{q.size} OFFSET #{q.offset}
</select>

<select id="countMatching" resultType="long">
  SELECT count(*)
  FROM   customer_order o
  JOIN   customer c ON c.customer_id = o.customer_id
  <include refid="searchFilters"/>
</select>
Never build SQL with ${}

#{} produces a bind parameter; ${} pastes text straight into the statement and is a SQL-injection hole. Sorting is the usual temptation — handle it by mapping a client-supplied key to a fixed allow-list of column names in Java, never by interpolating the raw value.

Keyset paging for deep pages

OFFSET 50000 reads 50,000 rows and throws them away
<select id="searchAfter" resultType="OrderSummary">
  SELECT o.order_id AS id, o.reference, o.status,
         o.total_amount AS totalAmount, o.placed_at AS placedAt
  FROM   customer_order o
  <where>
    <if test="cursorPlacedAt != null">
      AND (o.placed_at, o.order_id) < (#{cursorPlacedAt}, #{cursorId})
    </if>
  </where>
  ORDER BY o.placed_at DESC, o.order_id DESC
  LIMIT #{size}
</select>

The row-value comparison matches idx_order_keyset exactly, so page 5,000 costs the same as page 1. Use offset paging for the UI's numbered pages and keyset for exports and infinite scroll.

Writes, optimistic locking and batching

OrderMapper.xml — mutations
<insert id="insert" useGeneratedKeys="true" keyProperty="id" keyColumn="order_id">
  INSERT INTO customer_order (customer_id, status, total_amount, currency, metadata)
  VALUES (#{customerId}, #{status}::order_status, #{totalAmount}, #{currency},
          #{metadata, typeHandler=JsonTypeHandler})
</insert>

<insert id="insertLines">
  INSERT INTO order_line (order_id, product_id, quantity, unit_price)
  VALUES
  <foreach collection="lines" item="l" separator=",">
    (#{orderId}, #{l.productId}, #{l.quantity}, #{l.unitPrice})
  </foreach>
</insert>

<update id="updateStatus">
  UPDATE customer_order
  SET    status     = #{to}::order_status,
         version    = version + 1,
         updated_at = now(),
         placed_at  = COALESCE(placed_at,
                        CASE WHEN #{to} != 'DRAFT' THEN now() END)
  WHERE  order_id = #{id}
    AND  version  = #{expectedVersion}
</update>
Optimistic locking in one line

updateStatus returns the affected row count. 0 means somebody else changed the order since it was read — the service turns that into HTTP 409 Conflict. No pessimistic SELECT … FOR UPDATE, no held locks, no deadlocks.

A type handler for jsonb

common/JsonTypeHandler.java
@MappedTypes(Map.class)
public class JsonTypeHandler extends BaseTypeHandler<Map<String, Object>> {

    private static final ObjectMapper MAPPER = new ObjectMapper();
    private static final TypeReference<Map<String, Object>> TYPE = new TypeReference<>() {};

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i,
                                    Map<String, Object> value, JdbcType jdbcType)
            throws SQLException {
        PGobject o = new PGobject();
        o.setType("jsonb");
        o.setValue(write(value));
        ps.setObject(i, o);
    }

    @Override
    public Map<String, Object> getNullableResult(ResultSet rs, String column)
            throws SQLException {
        return read(rs.getString(column));
    }
    // remaining overloads delegate to read(...)

    private static String write(Map<String, Object> v) {
        try { return MAPPER.writeValueAsString(v); }
        catch (JsonProcessingException e) { throw new IllegalStateException(e); }
    }
    private static Map<String, Object> read(String json) {
        if (json == null) return new LinkedHashMap<>();
        try { return MAPPER.readValue(json, TYPE); }
        catch (JsonProcessingException e) { throw new IllegalStateException(e); }
    }
}
application.yml — register it
mybatis:
  mapper-locations: classpath*:com/bitsnippets/oms/**/*Mapper.xml
  type-aliases-package: com.bitsnippets.oms
  type-handlers-package: com.bitsnippets.oms.common
  configuration:
    map-underscore-to-camel-case: true
    default-executor-type: reuse

Testing against a real database

OrderMapperTest.java
@SpringBootTest
@Testcontainers
@Transactional   // rolls back after each test
class OrderMapperTest {

    @Container
    @ServiceConnection
    static PostgreSQLContainer<?> db = new PostgreSQLContainer<>("postgres:16-alpine");

    @Autowired OrderMapper mapper;

    @Test
    void loadsAggregateInOneQuery() {
        Order order = mapper.findById(1L).orElseThrow();
        assertThat(order.getLines()).hasSize(3);
        assertThat(order.getTotalAmount())
            .isEqualByComparingTo(order.getLines().stream()
                .map(OrderLine::lineTotal)
                .reduce(BigDecimal.ZERO, BigDecimal::add));
    }

    @Test
    void staleVersionUpdatesNothing() {
        assertThat(mapper.updateStatus(1L, OrderStatus.PAID, 99)).isZero();
    }
}
Never use H2 to test PostgreSQL SQL

jsonb, enums, ILIKE, row-value comparisons and generated columns all behave differently or not at all. Testcontainers starts the real thing in a couple of seconds and reuses the container across the suite.

findById returns three Order objects instead of one order with three lines. What is missing?

MyBatis uses the <id> column to decide whether a row belongs to the object it just built. Without it, every joined row looks like a new Order.