Mybatis 结合Java 8 Optional查询优雅处理空指针
程序员文章站
2022-06-07 18:34:42
...
Mybatis 结合Optional查询优雅处理空指针
场景
结合Java 8的Optional处理查询数据,减少Controller或Service调用方法的空指针判断,让调用方代码更优雅处理数据
准备
必须mybatis-3.5.0
版本以上,本人用以下maven版本的依赖
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.8</version>
</dependency>
Mapper代码
Optional <VnSku> findOne(@Param("id") Long id);
Mapper XML
<select id="findOne" resultType="com.earl.model.VnSku">
SELECT *
FROM vn_sku
WHERE id = #{id}
</select>
Service 实现调用逻辑
@Autowired
private VnSkuMapper vnSkuMapper;
public VnSku findOne(Long id) {
Optional < VnSku > optional = vnSkuMapper.findOne(id);
//若数据不存在直接抛异常
return optional.orElseThrow(()-> new ServiceException("数据不存在"));
}
Controller进行调用
假设获取某个商品的数量字段计算
@Autowired
private VnSkuService vnSkuService;
@GetMapping("/sku-num/{id}")
public Response getSkuTotalNum(@PathVariable("id")Long id ) {
VnSku data = vnSkuService.findOne(id);
return Response.success().setData(data.getNum() + 5);
}