Master MyBatis with Spring Boot: Setup, Configuration, and CRUD Guide
This tutorial walks through integrating MyBatis with Spring Boot, covering Maven dependencies, datasource configuration, mapper scanning, basic CRUD XML mappings, the differences between #{ } and ${ }, auto‑generated key handling, SQL fragments, and enabling camel‑case mapping for seamless Java‑to‑database interaction.
Introduction
As an experienced backend developer, the author compares Hibernate and MyBatis, then introduces a step‑by‑step guide to using MyBatis.
What is MyBatis
MyBatis is a persistence framework that supports custom SQL, stored procedures, and advanced mapping. It eliminates most JDBC boilerplate and can be configured via XML or annotations to map POJOs to database records.
Environment Setup
The tutorial uses Spring Boot, MyBatis, and MySQL. Required Maven dependencies include the MySQL driver, Druid connection pool, and the MyBatis Spring Boot starter.
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.40</version>
<scope>runtime</scope>
</dependency>
<!-- Druid connection pool -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.9</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>Druid datasource properties are set in application.properties:
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/vivachekcloud_pzhdermyy?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.druid.initial-size=0
spring.datasource.druid.max-active=20
spring.datasource.druid.min-idle=0
spring.datasource.druid.max-wait=6000
spring.datasource.druid.validation-query=SELECT 1
spring.datasource.druid.test-on-borrow=false
spring.datasource.druid.test-on-return=false
spring.datasource.druid.test-while-idle=true
spring.datasource.druid.time-between-eviction-runs-millis=60000
spring.datasource.druid.min-evictable-idle-time-millis=25200000
spring.datasource.druid.removeAbandoned=true
spring.datasource.druid.remove-abandoned-timeout=1800
spring.datasource.druid.log-abandoned=true
spring.datasource.druid.filters=mergeStat
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000Basic Concepts
daolayer stores interfaces that interact with the database. service layer contains business‑logic classes.
Mapper XML Location
MyBatis expects mapper XML files to reside in the same package as the corresponding interface and share the same name. With Spring Boot, the location can be configured as:
mybatis.mapper-locations=classpath*:/mapper/**/*.xmlConfiguration Classes
Spring Boot auto‑configures MyBatis via MybatisAutoConfiguration. The related properties are defined in MybatisProperties:
@Configuration
@ConditionalOnClass({ SqlSessionFactory.class, SqlSessionFactoryBean.class })
@ConditionalOnSingleCandidate(DataSource.class)
@EnableConfigurationProperties(MybatisProperties.class)
@AutoConfigureAfter(DataSourceAutoConfiguration.class)
public class MybatisAutoConfiguration implements InitializingBean { } public class MybatisProperties {
public static final String MYBATIS_PREFIX = "mybatis";
private String configLocation;
private String[] mapperLocations;
}Scanning Mapper Interfaces
Two options exist:
Annotate each mapper interface with @Mapper.
@Mapper
public interface UserInfoMapper {
int insert(UserInfo record);
int insertSelective(UserInfo record);
}Use @MapperScan on a configuration class to scan a package.
@MapperScan({"com.xxx.dao"})
public class ApiApplication { }Do not mix both annotations on the same project.
Basic CRUD
Select
Example of a select statement and its Java method:
<select id="selectPersonById" parameterType="int" resultType="com.myjszl.domain.Person">
SELECT name, age, id FROM PERSON WHERE ID = #{id}
</select> Person selectPersonById(int id);Insert / Update / Delete
Typical XML snippets for data modification:
<insert id="insertAuthor">
insert into Author(id,username,password,email,bio)
values (#{id},#{username},#{password},#{email},#{bio})
</insert>
<update id="updateAuthor">
update Author set
username = #{username},
password = #{password},
email = #{email},
bio = #{bio}
where id = #{id}
</update>
<delete id="deleteAuthor">
delete from Author where id = #{id}
</delete>#{} vs ${}
#{}uses JDBC prepared statements, preventing SQL injection; ${} performs literal string substitution and is unsafe.
Returning Generated Keys
To obtain an auto‑incremented primary key after an insert, set useGeneratedKeys="true" and specify keyProperty="id":
<insert id="addPerson" parameterType="com.xxx.domain.Person" useGeneratedKeys="true" keyProperty="id">
insert into person(name,age) values(#{name},#{age});
</insert>SQL Fragments
Define reusable snippets with <sql> and include them elsewhere:
<sql id="userColumns">${alias}.id,${alias}.username,${alias}.password</sql>
<select id="selectUsers" resultType="map">
select
<include refid="userColumns"><property name="alias" value="t1"/></include>,
<include refid="userColumns"><property name="alias" value="t2"/></include>
from some_table t1 cross join some_table t2
</select>Camel‑Case Mapping
Enable automatic mapping from underscore column names to camel‑case Java properties by adding the following line to application.properties:
mybatis.configuration.map-underscore-to-camel-case=trueConclusion
The article provides a beginner‑level guide to integrating MyBatis with Spring Boot, covering environment setup, Maven dependencies, datasource configuration, mapper scanning, basic CRUD XML mappings, key differences between parameter syntaxes, auto‑generated key handling, reusable SQL fragments, and camel‑case mapping.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Code Ape Tech Column
Former Ant Group P8 engineer, pure technologist, sharing full‑stack Java, job interview and career advice through a column. Site: java-family.cn
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
