Mybatis 3.5
发布有段时间了,终于支持了 Optional
,这么实用的特性,居然还没人安利……因而本文出现了。git
文章比较简单,但很是实用,由于能大量简化恶心的判空代码。github
WARNINGredis
因为本文很是简(low)单(比),我相信又会有相似以下的大佬出现(最近莫名其妙地被若干大佬喷,也不知道得罪谁了,必须高能预警一下,省得脏了大佬们的眼睛):spring
- 嫌低级喷:”这么简单文章也好意思写,没有源码分析好意思拿出来!”——我源码分析的文章也有小几十篇了,阅读量更差。并且我写文也不纯粹迎合观众,我以为有用,有价值,就总结下,之后本身也好备忘,仅此而已。
- 秀优越感喷:”你的文章没有价值,看看我这篇”——真人真事,在某技术群讨论,吐槽了一圈后,贴出本身同类文章(带源码分析),对这种只能献上本身的膝盖,尊称100声大佬。
- 无脑喷:”你的文章就是一坨屎”——你才是一坨屎,没人逼着你看啊,本身找不开心啊咋地。
OK,预防针打过了,开始正文吧——编程
TIPSmybatis
简单起见——app
- 本文直接用Mybaits的注解式编程,不把SQL独立放在xml文件了
- 省略Service,直接Controller调用DAO
相信你们使用Mybatis时代码是这样写的:spring-boot
@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啦!你的代码能够这么写了:this
@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/