Loading

Quipoin Menu

Learn • Practice • Grow

spring / MyBatis Integration
interview

Q1. What is MyBatis?
MyBatis is a persistence framework that maps Java objects to SQL statements using XML or annotations. Unlike ORMs that generate SQL, MyBatis gives you full control over SQL. It's useful when you need to work with complex queries or legacy databases.

Q2. How do you integrate MyBatis with Spring?
Use MyBatis-Spring adapter. Define SqlSessionFactoryBean with DataSource and mapper locations. Then define mapper interfaces using @MapperScan or MapperFactoryBean. Example:
@Bean public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception { SqlSessionFactoryBean factory = new SqlSessionFactoryBean(); factory.setDataSource(dataSource); return factory.getObject(); }

Q3. What is a mapper in MyBatis?
A mapper is an interface that defines methods for database operations. Each method is mapped to an SQL statement via XML or annotations. Spring can inject mapper proxies into your services.

Q4. How do you define SQL in MyBatis using annotations?
Use annotations like @Select, @Insert, @Update, @Delete on mapper methods. Example:
@Select("SELECT * FROM users WHERE id = #{id}") User getUser(Long id);

Q5. What are the advantages of MyBatis over JPA?
MyBatis gives you full control over SQL, making it easier to optimize complex queries. It's lighter and more straightforward for teams comfortable with SQL. However, it requires more manual mapping and doesn't offer the same level of abstraction as JPA.