https://mp.weixin.qq.com/s/u8ovgcauDwq6Qc_8AfQncA
相信大家使用Mybatis时代码是这样写的:
@Maper
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) {
// 抛异常,或者做点其他事情
}
}
}
After
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<实体类>
。•国内最流行的第三方Mybaits增强 Mybatis通用Mapper[1] ,及其配套的 通用Mapper专用生成器[2] 都尚未支持Optional
,笔者提Issue,详见:建议支持Optional[3] ,其实想支持很简单,只需稍作修改即可。看最近时间,考虑提交PR。