MyBatis with Spring Boot
One dependency, four YAML lines and an annotation. The starter removes the configuration file entirely — which is convenient right up to the moment you need to know what it did. This chapter covers both.
The dependency
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>3.0.3</version> </dependency> <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <scope>runtime</scope> </dependency>
Starter 3.0.x targets Spring Boot 3 / Spring Framework 6 / Jakarta EE.
Starter 2.3.x targets Spring Boot 2.7 and javax. They are not
interchangeable, and mixing them produces NoClassDefFoundError on
javax.sql or jakarta.annotation classes at startup.
What the auto-configuration provides
- A
SqlSessionFactorybuilt from the SpringDataSource. - A
SqlSessionTemplate— thread-safe, transaction-aware, shared by all mappers. - Scanning for
@Mapperinterfaces and a proxy bean for each one. - Registration of
SpringManagedTransactionFactory, so MyBatis joins the Spring transaction rather than starting its own. - Mapper XML discovery from
mybatis.mapper-locations.
Configuration
spring:
application:
name: shop-service
datasource:
url: jdbc:postgresql://localhost:5432/shop
username: shop_app
password: ${DB_PASSWORD}
hikari:
maximum-pool-size: 20
minimum-idle: 5
connection-timeout: 3000
leak-detection-threshold: 20000
mybatis:
# where the XML lives (Ant patterns)
mapper-locations: classpath*:com/bitsnippets/shop/mapper/*.xml
# short names for resultType
type-aliases-package: com.bitsnippets.shop.domain
# custom TypeHandlers, scanned
type-handlers-package: com.bitsnippets.shop.handler
# everything from <settings>, in kebab-case
configuration:
map-underscore-to-camel-case: true
default-statement-timeout: 30
default-fetch-size: 200
cache-enabled: false
auto-mapping-unknown-column-behavior: WARNING
call-setters-on-nulls: true
logging:
level:
com.bitsnippets.shop.mapper: DEBUG
| Property | Replaces |
|---|---|
mybatis.config-location | Keeps a real mybatis-config.xml — mutually exclusive with mybatis.configuration.* |
mybatis.mapper-locations | <mappers><mapper resource> |
mybatis.type-aliases-package | <typeAliases><package> |
mybatis.type-handlers-package | <typeHandlers><package> |
mybatis.configuration.* | <settings> |
mybatis.executor-type | defaultExecutorType |
Setting both throws “Property 'configuration' and 'configLocation' can not specified with together” at startup. Pick the YAML route or the XML route.
Registering mappers
@Mapper
public interface UserMapper {
Optional<User> findById(Long id);
}
Explicit and greppable. Requires the interface to be under the application's component scan base package.
@SpringBootApplication
@MapperScan(basePackages = "com.bitsnippets.shop.mapper",
annotationClass = Mapper.class)
public class ShopApplication {
public static void main(String[] args) {
SpringApplication.run(ShopApplication.class, args);
}
}
Necessary when mappers live outside the scanned packages, or in a library module.
annotationClass prevents the scanner from proxying unrelated interfaces.
A complete vertical slice
@RestController
@RequestMapping("/api/users")
public class UserController {
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping("/{id}")
public UserResponse get(@PathVariable Long id) {
return UserResponse.from(userService.require(id));
}
@GetMapping
public PageResponse<UserResponse> search(
@RequestParam(required = false) String q,
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "25") int size) {
UserQuery query = new UserQuery();
query.setNameLike(q);
query.setLimit(Math.min(size, 200));
query.setOffset(page * size);
return PageResponse.from(userService.search(query));
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public UserResponse create(@Valid @RequestBody CreateUserRequest request) {
return UserResponse.from(
userService.register(request.userName(), request.email()));
}
}
@Service
public class UserService {
private final UserMapper userMapper;
public UserService(UserMapper userMapper) {
this.userMapper = userMapper;
}
@Transactional(readOnly = true)
public User require(Long id) {
return userMapper.findById(id)
.orElseThrow(() -> new UserNotFoundException(id));
}
@Transactional(readOnly = true)
public PageResult<User> search(UserQuery query) {
return new PageResult<>(userMapper.search(query),
userMapper.countSearch(query),
query.getOffset() / query.getLimit(),
query.getLimit());
}
@Transactional
public User register(String userName, String email) {
if (userMapper.existsByEmail(email)) {
throw new DuplicateEmailException(email);
}
User user = new User();
user.setUserName(userName);
user.setEmail(email);
user.setStatus("ACTIVE");
userMapper.insert(user);
return user;
}
}
It lets the JDBC driver skip dirty-checking work and, more importantly, allows routing to
a read replica via a AbstractRoutingDataSource. It also documents intent for
the next reader.
Exception translation
MyBatisExceptionTranslator converts SQLException into Spring's
DataAccessException hierarchy, so your service code never imports
java.sql.
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(DuplicateKeyException.class)
@ResponseStatus(HttpStatus.CONFLICT)
public ApiError duplicate(DuplicateKeyException e) {
return new ApiError("DUPLICATE", "That value already exists");
}
@ExceptionHandler(UserNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public ApiError notFound(UserNotFoundException e) {
return new ApiError("NOT_FOUND", e.getMessage());
}
@ExceptionHandler(QueryTimeoutException.class)
@ResponseStatus(HttpStatus.GATEWAY_TIMEOUT)
public ApiError timeout(QueryTimeoutException e) {
return new ApiError("DB_TIMEOUT", "The query took too long");
}
}
Multiple data sources
The auto-configuration backs off entirely once you define your own beans. Each data source needs its own factory, template, transaction manager and mapper scan — kept apart by base package.
@Configuration
@MapperScan(basePackages = "com.bitsnippets.shop.mapper.primary",
sqlSessionTemplateRef = "primarySqlSessionTemplate")
public class PrimaryDbConfig {
@Bean
@Primary
@ConfigurationProperties("app.datasource.primary")
public DataSourceProperties primaryDataSourceProperties() {
return new DataSourceProperties();
}
@Bean
@Primary
public DataSource primaryDataSource(DataSourceProperties properties) {
return properties.initializeDataSourceBuilder()
.type(HikariDataSource.class)
.build();
}
@Bean
@Primary
public SqlSessionFactory primarySqlSessionFactory(DataSource dataSource)
throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setTypeAliasesPackage("com.bitsnippets.shop.domain");
bean.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources("classpath*:mapper/primary/*.xml"));
org.apache.ibatis.session.Configuration cfg =
new org.apache.ibatis.session.Configuration();
cfg.setMapUnderscoreToCamelCase(true);
bean.setConfiguration(cfg);
return bean.getObject();
}
@Bean
@Primary
public SqlSessionTemplate primarySqlSessionTemplate(SqlSessionFactory factory) {
return new SqlSessionTemplate(factory);
}
@Bean
@Primary
public PlatformTransactionManager primaryTxManager(DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
}
app:
datasource:
primary:
url: jdbc:postgresql://primary:5432/shop
username: shop_app
password: ${DB_PASSWORD}
reporting:
url: jdbc:postgresql://replica:5432/shop
username: shop_read
password: ${DB_READ_PASSWORD}
A @Transactional method uses one manager. Writing to both databases in
a single method gives you two independent transactions, either of which can fail alone.
If you need real atomicity across them you are in XA territory — usually a sign the
design should change instead.
Observability
management:
endpoints:
web:
exposure:
include: health,metrics,prometheus
metrics:
tags:
application: ${spring.application.name}
health:
db:
enabled: true
Useful metrics out of the box: hikaricp.connections.active,
hikaricp.connections.pending, hikaricp.connections.timeout. Pending
connections above zero for any sustained period means your pool is too small or a query is
too slow. Chapter 12 shows a plugin that adds per-statement timing.
Startup checklist
- Starter version matches your Boot major version.
mapper-locationsusesclasspath*:if mappers come from several jars.map-underscore-to-camel-caseis on.- A statement timeout and a pool leak-detection threshold are set.
- Every service method that writes is
@Transactional; read paths arereadOnly. - Mapper logger is at
DEBUGin dev and test,INFOin production.
You defined your own DataSource bean. What happens to
mybatis.configuration.* in application.yml?
Those properties are consumed by MybatisAutoConfiguration, which backs off as
soon as a SqlSessionFactory bean exists. Once you construct the factory in your
own @Configuration, you must apply the settings on the
Configuration object yourself.