Prev Next

Hibernate / MyBatis Interview questions

1. What is MyBatis? 2. What is the purpose of MyBatis? 3. What are the key features of MyBatis? 4. What is the difference between MyBatis and Hibernate? 5. What is a SqlSessionFactory in MyBatis? 6. What is a SqlSession in MyBatis? 7. What is a Mapper interface in MyBatis? 8. What is the mybatis-config.xml file used for? 9. What is a Mapper XML file? 10. How do you write a basic SELECT statement in MyBatis? 11. What is parameter binding in MyBatis? 12. What is result mapping? 13. What are the supported statement types in MyBatis? 14. What is the difference between #{} and ${} in MyBatis? 15. What is a resultMap? 16. How do you configure a data source in MyBatis? 17. What is MyBatis-Spring? 18. How do you integrate MyBatis with Spring Boot? 19. What is dynamic SQL in MyBatis? 20. List the dynamic SQL elements available in MyBatis? 21. What is the difference between MyBatis and JPA/Hibernate in terms of philosophy? 22. Why is #{} preferred over ${} for parameter binding? 23. How does MyBatis prevent SQL injection? 24. What is the difference between resultType and resultMap? 25. What is the @Param annotation used for in MyBatis? 26. Explain how MyBatis handles one-to-many mappings? 27. Explain how MyBatis handles many-to-one mappings? 28. What is the difference between association and collection in resultMap? 29. What is lazy loading in MyBatis, and how do you configure it? 30. Explain the lifecycle of a SqlSession? 31. What is the difference between SqlSessionFactory and SqlSessionFactoryBuilder? 32. How does MyBatis's first-level cache work? 33. How does MyBatis's second-level cache work? 34. What is the difference between first-level and second-level cache? 35. Explain how to implement a custom TypeHandler in MyBatis? 36. What is the purpose of the if, choose, when, otherwise dynamic SQL elements? 37. Explain the internal working of the foreach element for batch operations? 38. How do you handle batch inserts/updates in MyBatis? 39. What is the Mapper proxy pattern, and how does MyBatis use it internally? 40. Explain the execution flow of a MyBatis query from mapper call to result? 41. What is the difference between MyBatis annotations and XML mapping? 42. How do you use MyBatis with multiple data sources? 43. Explain the role of the Executor in MyBatis's internal architecture, including the SIMPLE, REUSE, and BATCH executor types? 44. How does MyBatis handle transactions, and how does it integrate with Spring's transaction management? 45. What is a plugin/interceptor in MyBatis, and how do you write one? 46. Explain how pagination is typically implemented in MyBatis? 47. What is the N+1 select problem, and how does it relate to MyBatis? 48. How do you troubleshoot a MyBatis mapping exception? 49. Explain the internal working of MyBatis's dynamic SQL parsing? 50. Explain the execution flow of MyBatis-Spring-Boot-Starter's auto-configuration?

1. What is MyBatis?

MyBatis is an open-source Java persistence framework that maps SQL statements to Java methods, letting developers write and control their own SQL directly while MyBatis handles the mechanical work of parameter binding, executing the statement, and mapping the result set...

Read full answer

2. What is the purpose of MyBatis?

MyBatis exists to eliminate the repetitive boilerplate of manually working with JDBC — opening connections, preparing statements, binding parameters one by one, iterating a ResultSet, and mapping columns into object fields by hand — while still giving developers full, direct...

Read full answer

3. What are the key features of MyBatis?

MyBatis combines a focused set of capabilities aimed specifically at making hand-written SQL easier to work with from Java, without taking over SQL generation the way a full ORM does. Feature What it Provides SQL mapping Maps hand-written SQL statements...

Read full answer

4. What is the difference between MyBatis and Hibernate?

Both are Java persistence frameworks, but they represent fundamentally different philosophies: MyBatis is a SQL mapper that keeps hand-written SQL front and center, while Hibernate is a full object-relational mapping (ORM) framework that generates SQL automatically from an object model....

Read full answer

5. What is a SqlSessionFactory in MyBatis?

A SqlSessionFactory is the central factory object responsible for creating SqlSession instances, built once from MyBatis's configuration (data source settings, mapper registrations, type handlers) and then reused for the lifetime of the application, rather than being recreated for every database

Read full answer

6. What is a SqlSession in MyBatis?

A SqlSession is the primary interface for executing SQL commands, retrieving mappers, and managing transactions in MyBatis, created from a SqlSessionFactory and representing a single, typically short-lived unit of work against the database. try (SqlSession session = sqlSessionFactory.openSession(

Read full answer

7. What is a Mapper interface in MyBatis?

A Mapper interface is a plain Java interface whose methods correspond to SQL statements defined either in a matching XML mapper file or directly via annotations, and MyBatis automatically generates a working implementation of that interface at runtime — no...

Read full answer

8. What is the mybatis-config.xml file used for?

The mybatis-config.xml file is MyBatis's top-level, global configuration file, holding settings that apply across the entire application — environment/data source configuration, type aliases, plugin registrations, and the list of mapper files or interfaces to load — distinct from the

Read full answer

9. What is a Mapper XML file?

A Mapper XML file defines the actual SQL statements for a given mapper namespace, associating each statement with an id that corresponds to a method on the matching Mapper interface, along with the parameter and result type information MyBatis needs...

Read full answer

10. How do you write a basic SELECT statement in MyBatis?

A basic SELECT statement in MyBatis is defined inside a <select> element within a Mapper XML file, specifying an id matching a Mapper interface method, along with the parameter type it accepts and the result type it returns. <select id=...

Read full answer

11. What is parameter binding in MyBatis?

Parameter binding is the process of substituting Java method arguments into placeholders within a SQL statement, using the #{} syntax to reference a parameter by name (or by property, for object parameters), which MyBatis translates into a safely parameterized JDBC...

Read full answer

12. What is result mapping?

Result mapping is the process of translating columns in a SQL query's result set into fields or properties of a Java object, which MyBatis can do automatically for simple cases (matching column names to bean property names) or explicitly via...

Read full answer

13. What are the supported statement types in MyBatis?

MyBatis provides four core XML elements (and their annotation equivalents) corresponding to the standard SQL data manipulation operations, each with slightly different default behaviors around what they return. Element / Annotation SQL Operation Typical Return <select> / @Select SELECT A...

Read full answer

14. What is the difference between #{} and ${} in MyBatis?

Both syntaxes substitute a value into a SQL statement, but they work through fundamentally different mechanisms with very different safety implications &mdash; a distinction that's one of the most commonly tested MyBatis interview topics for good reason. #{} ${} Compiled...

Read full answer

15. What is a resultMap?

A resultMap is an explicit, named mapping definition in a Mapper XML file that describes how the columns of a query's result set correspond to the properties of a Java object, used whenever the automatic, name-matching mapping behind a simple...

Read full answer

16. How do you configure a data source in MyBatis?

In a plain, non-Spring MyBatis application, a data source is configured inside the <environments> element of mybatis-config.xml, specifying connection details and which pooling strategy MyBatis should use to manage database connections. <dataSource type= "POOLED" > <property name= "driver" value=

Read full answer

17. What is MyBatis-Spring?

MyBatis-Spring is the integration library that lets MyBatis participate cleanly in a Spring application &mdash; wiring MyBatis's SqlSessionFactory and mapper beans into the Spring container, and critically, letting MyBatis operations participate in Spring's own transaction management rather than

Read full answer

18. How do you integrate MyBatis with Spring Boot?

Integrating MyBatis with Spring Boot typically means adding the mybatis-spring-boot-starter dependency, which brings in MyBatis, MyBatis-Spring, and Spring Boot auto-configuration that wires up a SqlSessionFactory and mapper scanning automatically based on sensible defaults and application proper

Read full answer

19. What is dynamic SQL in MyBatis?

Dynamic SQL refers to a set of XML elements MyBatis provides for conditionally building a SQL statement's structure at execution time based on which parameters are actually present or what values they hold, rather than needing to write out every...

Read full answer

20. List the dynamic SQL elements available in MyBatis?

MyBatis provides a specific set of XML tags for building dynamic SQL, each addressing a different conditional or structural need common in real-world queries. Element Purpose <if> Conditionally includes a SQL fragment based on a test expression <choose>/<when>/<otherwise> Switch-like conditional

Read full answer

21. What is the difference between MyBatis and JPA/Hibernate in terms of philosophy?

The core philosophical divide is where control over SQL generation sits: JPA/Hibernate treats the object model as the primary artifact and derives SQL from it automatically, while MyBatis treats SQL itself as the primary artifact and maps it explicitly to...

Read full answer

22. Why is #{} preferred over ${} for parameter binding?

#{} is preferred as the default because it compiles down to a JDBC PreparedStatement placeholder, meaning the actual value is sent to the database separately from the SQL statement's structure, which is what fundamentally prevents SQL injection &mdash; the database...

Read full answer

23. How does MyBatis prevent SQL injection?

MyBatis itself doesn't actively scan for or block malicious input &mdash; its protection comes from encouraging (and defaulting most examples and generated code toward) the #{} parameter binding syntax, which relies on JDBC's own PreparedStatement mechanism to keep SQL structure...

Read full answer

24. What is the difference between resultType and resultMap?

Both attributes tell MyBatis how to map a query's result set to Java objects, but they differ in how that mapping is expressed: resultType is a shorthand for simple, automatic mapping, while resultMap references an explicit, reusable mapping definition. resultType...

Read full answer

25. What is the @Param annotation used for in MyBatis?

The @Param annotation assigns an explicit name to a Mapper interface method parameter, which is needed whenever a statement takes more than one simple parameter, since #{} placeholders in the SQL need to reference each parameter by a name that...

Read full answer

26. Explain how MyBatis handles one-to-many mappings?

A one-to-many relationship &mdash; like one order having many line items &mdash; is expressed in a resultMap using the <collection> element, which tells MyBatis to gather multiple related rows into a Java List (or other collection type) nested inside the...

Read full answer

27. Explain how MyBatis handles many-to-one mappings?

A many-to-one relationship &mdash; like many orders each belonging to one customer &mdash; is expressed using the <association> element within a resultMap, mapping a single nested object rather than a collection, since each parent row corresponds to at most one...

Read full answer

28. What is the difference between association and collection in resultMap?

Both elements map a nested, related object within a parent resultMap, but they differ in cardinality &mdash; exactly matching the distinction between a many-to-one/one-to-one relationship and a one-to-many relationship. association collection Maps a single nested object....

Read full answer

29. What is lazy loading in MyBatis, and how do you configure it?

Lazy loading defers fetching an associated object or collection until the moment it's actually accessed in application code, rather than fetching it eagerly as part of the initial query, which can avoid unnecessary work when a related object isn't always...

Read full answer

30. Explain the lifecycle of a SqlSession?

A SqlSession moves through a defined, short-lived lifecycle: created from a SqlSessionFactory, used to execute one or more statements (typically within a single logical unit of work), and then explicitly closed, with the details of commit/rollback timing depending on whether...

Read full answer

31. What is the difference between SqlSessionFactory and SqlSessionFactoryBuilder?

These are two distinct objects in MyBatis's bootstrap process, each with a narrow, single-purpose role: the builder constructs a factory from configuration, and the factory then produces sessions on an ongoing basis. SqlSessionFactoryBuilder SqlSessionFactory A one-time-use builder that reads con

Read full answer

32. How does MyBatis's first-level cache work?

The first-level cache is a session-scoped cache, enabled by default and not independently configurable off, that stores the results of queries executed within a single SqlSession &mdash; if the exact same query with the exact same parameters is executed again...

Read full answer

33. How does MyBatis's second-level cache work?

The second-level cache is an optional, mapper-scoped (namespace-scoped) cache that persists across sessions, storing query results so that different SqlSession instances executing the same query against the same mapper can share cached results rather than each hitting the database independently.

Read full answer

34. What is the difference between first-level and second-level cache?

Both caches avoid redundant database queries, but they differ substantially in scope, default status, and the kind of staleness risk they carry. First-Level Cache Second-Level Cache Scoped to a single SqlSession....

Read full answer

35. Explain how to implement a custom TypeHandler in MyBatis?

A TypeHandler controls how MyBatis converts between a Java type and a JDBC type during parameter binding and result mapping; a custom TypeHandler is needed when a Java type doesn't have built-in support, or when the default conversion behavior isn't...

Read full answer

36. What is the purpose of the if, choose, when, otherwise dynamic SQL elements?

These elements provide conditional branching logic within a SQL statement, mirroring familiar programming constructs &mdash; <if> as a simple conditional, and <choose> / <when> / <otherwise> together as a switch-like construct that picks exactly one matching branch. <select id= "findUsers"...

Read full answer

37. Explain the internal working of the foreach element for batch operations?

The <foreach> element iterates over a Java collection or array parameter, repeating a specified SQL fragment once per item and joining the repetitions with a configurable separator &mdash; most commonly used to build an IN () clause from a list...

Read full answer

38. How do you handle batch inserts/updates in MyBatis?

MyBatis supports batch operations two main ways: using the <foreach> element to build a single multi-row SQL statement, or using MyBatis's BATCH executor type to send multiple separate statements to the database together as one batch, reducing round-trip overhead compared...

Read full answer

39. What is the Mapper proxy pattern, and how does MyBatis use it internally?

MyBatis generates a working implementation of a Mapper interface at runtime using Java's dynamic proxy mechanism, rather than requiring a hand-written implementation class &mdash; when application code calls session.getMapper(UserMapper.class) , what's actually returned is a proxy object implemen

Read full answer

40. Explain the execution flow of a MyBatis query from mapper call to result?

A single mapper method call moves through several internal MyBatis layers before returning a mapped Java result, each responsible for a distinct part of translating a typed Java call into an executed SQL statement and back. flowchart TD A[Application calls...

Read full answer

41. What is the difference between MyBatis annotations and XML mapping?

Both approaches define the same underlying concept &mdash; SQL statements tied to Mapper interface methods &mdash; but they differ in where that definition lives and how well each scales to more complex mapping needs. Annotations XML Mapping SQL written directly...

Read full answer

42. How do you use MyBatis with multiple data sources?

Supporting multiple databases in a single MyBatis application generally means configuring a separate SqlSessionFactory (and corresponding DataSource) per database, with mappers explicitly associated with the correct factory rather than assuming a single, application-wide default. @Configuration @

Read full answer

43. Explain the role of the Executor in MyBatis's internal architecture, including the SIMPLE, REUSE, and BATCH executor types?

The Executor is the core internal component responsible for actually carrying out a statement's execution against the database, sitting between the SqlSession's public API and the lower-level StatementHandler/ParameterHandler/ResultSetHandler pipeline, and MyBatis supports three distinct Executor

Read full answer

44. How does MyBatis handle transactions, and how does it integrate with Spring's transaction management?

In plain, non-Spring MyBatis usage, transaction boundaries are managed directly through the SqlSession &mdash; an explicit commit() persists changes, an explicit rollback() discards them, and by default a session is not in auto-commit mode, meaning a developer is responsible for...

Read full answer

45. What is a plugin/interceptor in MyBatis, and how do you write one?

A MyBatis plugin is a custom interceptor that hooks into one of four specific internal interfaces &mdash; Executor, ParameterHandler, ResultSetHandler, or StatementHandler &mdash; letting a developer intercept and modify behavior at a specific stage of the query execution pipeline, such...

Read full answer

46. Explain how pagination is typically implemented in MyBatis?

MyBatis offers a built-in but limited mechanism, RowBounds , alongside more commonly used approaches that push pagination logic directly into the SQL itself or rely on a plugin to automate it, and understanding the trade-offs between them matters for building...

Read full answer

47. What is the N+1 select problem, and how does it relate to MyBatis?

The N+1 select problem occurs when fetching a list of N parent records triggers one additional query per parent to fetch each one's related data, resulting in 1 (for the parent list) plus N (one per parent's related data) separate...

Read full answer

48. How do you troubleshoot a MyBatis mapping exception?

MyBatis mapping errors generally fall into a handful of recurring categories, and working through them in a consistent order &mdash; from configuration issues to type mismatches &mdash; is usually faster than guessing at the root cause from the exception message...

Read full answer

49. 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 &mdash; one node type per dynamic SQL element...

Read full answer

50. Explain the execution flow of MyBatis-Spring-Boot-Starter's auto-configuration?

When mybatis-spring-boot-starter is on the classpath of a Spring Boot application, its auto-configuration class activates automatically (conditioned on a DataSource bean being present) and wires up the SqlSessionFactory, mapper scanning, and related beans without requiring explicit XML or Java co

Read full answer

«
»

Comments & Discussions