Best Practices and Pitfalls

Harry · 11 Sep 2026 · 9 views

Patterns That Scale

  • One mapper per entity or aggregate keeps files small and navigable.
  • Name statements after the method; namespaces must match interfaces.
  • Map results explicitly for anything beyond trivial selects.
  • Prefer #{} everywhere; reserve ${} for validated identifiers.
  • Turn on mapUnderscoreToCamelCase to match database style.

Common Pitfalls

  • Forgetting useGeneratedKeys: inserted objects have NULL ids.
  • N+1 select problems: fetching a list then a query per row. Fix with joins or result maps.
  • Dynamic SQL typos: test the generated SQL with the mapper's debug logging before worrying about data.
  • Second-level cache on mutable data: shares stale or, worse, shared objects.
  • Long transactions: keep them short; a held transaction blocks readers on many databases.

Debugging Tip

Set the MyBatis logger level to DEBUG to print the exact SQL and parameter binding:

logging.level.com.example.app.mapper=DEBUG

Key Points

  • Size mappers per aggregate; name things consistently.
  • Generated keys and explicit result maps prevent classic bugs.
  • Watch for N+1 and cache hazards.
  • DEBUG logging shows you exactly what runs.
Share this post:

Comments (0)

Please login or register to comment.