How MyBatis Auto-Configuration Works in Spring Boot 3
Baseline: Spring Boot 3.x, MyBatis Spring Boot Starter 3.x, MyBatis 3.5.x, and Java 17+. Boot 2's javax dependencies cannot be mixed with Boot 3's jakarta dependencies.
1. The Starter's Role
DataSource -> SqlSessionFactory -> SqlSessionTemplate -> Mapper 代理
Auto-configuration determines whether to create objects based on the classpath, existing beans, and configuration properties. For the current entry point, use the AutoConfiguration.imports file in the dependency package, configuration metadata, and condition evaluation reports as the source of truth; don't rely on the legacy spring.factories.
2. Minimal Configuration
mybatis:
mapper-locations: classpath:/mapper/**/*.xml
type-aliases-package: com.example.order.domain
configuration:
map-underscore-to-camel-case: true
default-statement-timeout: 5
@Mapper
public interface OrderMapper {
Order findById(long id);
}
3. Bean Creation Chain
Spring Boot creates the DataSource; MyBatis creates the SqlSessionFactory, loads XML mappers, type handlers, and plugins, and creates the SqlSessionTemplate. The mapper scanner registers the MapperFactoryBean; ultimately, it returns a mapper proxy.
Put @Transactional in the service layer. With multiple data sources, explicitly configure each SqlSessionFactory, the mapper scan scope, and the transaction manager. Use #{} parameter binding; ${} performs string concatenation and may only be used with allowlisted fields.