Mybatis 3.5 发布有段时间了,终于支持了 Optional ,这么实用的特性,竟然还没人安利……于是本文出现了。
由于本文非常简(low)单(比),我相信又会有类似如下的大佬出现(最近莫名其妙地被若干大佬喷,也不知道得罪谁了,必须高能预警一下,免得脏了大佬们的眼睛):
OK,预防针打过了,开始正文吧——
简单起见——
相信大家使用Mybatis时代码是这样写的:
@Mapper
public interface UserMapper {
@Select("select * from user where id = #{id}")
User selectById(Long id);
}
然后,业务代码是这样写的:
public class UserController {
@Autowired
private UserMapper userMapper;
@GetMapping("/{id}")
public User findById(@PathVariable Long id) {
User user = this.userMapper.selectById(id);
if(user == null) {
// 抛异常,或者做点其他事情
}
}
}
Mybatis 3.5支持Optional啦!你的代码可以这么写了:
@Mapper
public interface UserMapper {
@Select("select * from user where id = #{id}")
Optional<User> selectById(Long id);
}
然后,业务代码可以变成这样:
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 exit!"));
}
}
至于 Optional 怎么使用,本文不作赘述——JDK 12都发布了,你要我普及JDK 8的”新特性”吗?大家自行百度吧,百度很多了。关键词: Java 8 Optional 。
Mybatis 已支持 Optional , Mybatis Spring Boot Starter 也已跟进,引入如下依赖即可:
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.0.0</version> </dependency>
然而, Mybatis 的配套设施尚未跟进——
Mybatis Generator 插件还未跟进,这意味着目前使用该插件生成的代码依然不会返回 Optional ,例如 selectByPrimaryKey ,返回的依然是 实体类 ,而非 Optional<实体类> 。 Optional ,笔者提Issue,详见: 建议支持Optional ,其实想支持很简单,只需稍作修改即可。看最近时间,考虑提交PR。 Spring Data (jpa、redis、mongo…)花了很大力气重构(很多包名都换了,API名称也改了),率先支持了 Optional ,不得不说,在Java世界, Spring 确实走在前面,引领着Java圈子的潮流。
http://www.itmuch.com/other/mybatis-optional-support/