How MyBatis 3.5’s Optional Support Eliminates Boilerplate Null Checks
MyBatis 3.5 now supports Java's Optional in mapper methods, allowing developers to replace verbose null‑checking code with concise, expressive calls, while noting that MyBatis Generator and some third‑party mappers have not yet adopted this feature.
Before
Typical MyBatis code returns an entity and requires explicit null‑check.
@Mapper
public interface UserMapper {
@Select("select * from user where id = #{id}")
User selectById(Long id);
}Controller example with null check.
public class UserController {
@Autowired
private UserMapper userMapper;
@GetMapping("/{id}")
public User findById(@PathVariable Long id) {
User user = this.userMapper.selectById(id);
if (user == null) {
// throw exception or handle
}
}
}After
MyBatis 3.5 allows mapper methods to return Optional<User>, eliminating manual null‑checking code.
@Mapper
public interface UserMapper {
@Select("select * from user where id = #{id}")
Optional<User> selectById(Long id);
}Controller can now directly return the entity or throw an exception.
public class UserController {
@Autowired
private UserMapper userMapper;
@GetMapping("/{id}")
public User findById(@PathVariable Long id) {
return this.userMapper.selectById(id)
.orElseThrow(() -> new IllegalArgumentException("This user does not exist!"));
}
}The new Optional feature greatly reduces boiler‑plate null‑checking code.
Limitations
MyBatis Generator and popular third‑party mappers (e.g., MyBatis‑General‑Mapper) have not yet been updated to return Optional. Issues have been opened and may be resolved with a small PR.
Dependency
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>References
MyBatis General Mapper: https://github.com/abel533/Mapper
Generator wiki: https://github.com/abel533/Mapper/wiki/4.1.mappergenerator
Issue requesting Optional support: https://github.com/abel533/Mapper/issues/558
Demo project on GitHub: https://github.com/eacdy/spring-boot-study/tree/master/spring-boot-mybatis-optional
Demo on Gitee: https://gitee.com/itmuch/spring-boot-study/tree/master/spring-boot-mybatis-optional
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.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
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.
