Hibernate / MyBatis Interview questions
Explain the internal working of MyBatis's dynamic SQL parsing?
When MyBatis loads a Mapper XML file containing dynamic SQL elements, it doesn't treat the statement as a plain string; instead, it parses the XML structure into a tree of SqlNode objects — one node type per dynamic SQL element — that gets evaluated fresh for every statement execution, since the actual resulting SQL can differ depending on the parameters passed in.
Each dynamic element type maps to a corresponding SqlNode implementation — IfSqlNode, ForEachSqlNode, ChooseSqlNode, and so on — and a parent MixedSqlNode holds the overall tree structure; when a statement executes, this tree is traversed, with elements like IfSqlNode evaluating their OGNL test expression against the actual runtime parameter object to decide whether to include their contained SQL fragment in the final assembled output.
This tree is built once when the mapper XML is parsed at startup (an expensive, one-time operation), but traversed fresh on every single statement execution (a comparatively cheap operation), which is the same general build-once/execute-many pattern used throughout MyBatis's architecture to keep per-query overhead low despite the flexibility dynamic SQL provides.
More Related questions...