Using MyBatis3 Annotations to Replace XML Configuration: A Comprehensive Guide
This article provides a step‑by‑step tutorial on using MyBatis3 annotation‑based CRUD, mapping, and provider annotations to replace XML configuration in a Spring Boot project, covering basic annotations, result mapping, dynamic SQL, Maven dependencies, configuration files, entity classes, database scripts, controller code, and testing procedures.
The article introduces MyBatis3 annotation support as a way to gradually replace XML configuration, showing how @Select and @SelectProvider can be used to write SQL directly in Java code and handle dynamic queries for complex business needs.
Basic CRUD annotations – MyBatis provides @Select, @Insert, @Update, and @Delete for the majority of data‑access operations. An example interface demonstrates a simple @Select query without any XML:
@Mapper
public interface UserMapper {
@Select("select * from t_user")
List<User> list();
}Result mapping annotations – When column names do not follow the default underscore‑to‑camel‑case conversion, @Results and @Result can explicitly map database fields to object properties. The article shows a @Results example that maps USER_ID, USERNAME, PASSWORD, and PHONE_NUM to the corresponding fields in the User class.
@Results({
@Result(property = "userId", column = "USER_ID"),
@Result(property = "username", column = "USERNAME"),
@Result(property = "password", column = "PASSWORD"),
@Result(property = "mobileNum", column = "PHONE_NUM")
})
@Select("select * from t_user")
List<User> list();Advanced provider annotations – @SelectProvider, @InsertProvider, @UpdateProvider, and @DeleteProvider enable dynamic SQL generation via a separate Java class. The guide includes a @SelectProvider example that calls UserSqlProvider.listByUsername.
@SelectProvider(type = UserSqlProvider.class, method = "listByUsername")
List<User> listByUsername(String username);
public class UserSqlProvider {
public String listByUsername(String username) {
return "select * from t_user where username = #{username}";
}
}Step‑by‑step tutorial
1. Dependencies – Maven coordinates for Spring Boot Web, MyBatis Spring Boot Starter, MySQL driver, and test libraries are added.
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>2. Application configuration – The application.yml file enables the MyBatis underscore‑to‑camel‑case mapping and configures the datasource and SQL logging.
spring:
datasource:
url: jdbc:mysql://localhost:3306/socks?useSSL=false
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
mybatis:
configuration:
map-underscore-to-camel-case: true
logging:
level:
com.hehe.mapper: debug3. Data‑layer code – The UserMapper interface contains CRUD methods, @SelectProvider for dynamic SQL, and @Results for explicit column mapping.
package com.hehe.mapper;
@Mapper
public interface UserMapper {
@Select("select * from t_user")
List<User> list();
@SelectProvider(type = UserSqlProvider.class, method = "listByUsername")
List<User> listByUsername(String username);
@Results({
@Result(property = "userId", column = "USER_ID"),
@Result(property = "username", column = "USERNAME"),
@Result(property = "password", column = "PASSWORD"),
@Result(property = "mobileNum", column = "PHONE_NUM")
})
@Select("select * from t_user")
List<User> listSample();
}4. SQL provider – The UserSqlProvider class shows two ways to build SQL: a simple string return and a dynamic builder using MyBatis' SQL API.
public class UserSqlProvider {
public String listByUsername(String username) {
return "select * from t_user where username = #{username}";
}
public String getBadUser(@Param("username") String username, @Param("password") String password) {
return new SQL() {{
SELECT("*");
FROM("t_user");
if (username != null && password != null) {
WHERE("username like #{username} and password like #{password}");
} else {
WHERE("1=2");
}
}}.toString();
}
}5. Entity class – A plain Java User POJO with fields matching the database columns.
public class User {
private String userId;
private String username;
private String password;
private String mobileNum;
// getters & setters
}6. Database script – SQL statements to create the t_user table and insert two sample rows.
USE `SOCKS`;
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
`USER_ID` varchar(50),
`USERNAME` varchar(50),
`PASSWORD` varchar(50),
`PHONE_NUM` varchar(15)
);
INSERT INTO `t_user` VALUES ('1','admin','admin','15011791234');
INSERT INTO `t_user` VALUES ('2','roots','roots','18812342017');7. Controller layer – A Spring Boot @RestController exposing endpoints to list users, query by username, and perform login‑style lookups.
package com.hehe.controller;
@RestController
@RequestMapping("/user/*")
public class UserController {
@Autowired
UserMapper userMapper;
@GetMapping("list")
public List<User> list() { return userMapper.list(); }
@GetMapping("list/{username}")
public List<User> listByUsername(@PathVariable("username") String username) {
return userMapper.listByUsername(username);
}
@GetMapping("get/{username}/{password}")
public User get(@PathVariable("username") String username,
@PathVariable("password") String password) {
return userMapper.get(username, password);
}
}8. Running and testing – After starting the Spring Boot application, the endpoints http://localhost:8080/user/list and http://localhost:8080/user/list/admin return the full user list and the record for the user admin, respectively.
9. Source code and documentation – The complete project is hosted at https://github.com/yizhiwazi/springboot-socks , and the official MyBatis Java API documentation can be found at http://www.mybatis.org/mybatis-3/zh/java-api.html .
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.
Java Captain
Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.
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.
