Mybatis 3.5 發佈有段時間了,終於支持了 Optional ,這麼實用的特性,竟然還沒人安利……於是本文出現了。
文章比較簡單,但非常實用,因爲能大量簡化噁心的判空代碼。
TIPS
簡單起見——
- 本文直接用Mybaits的註解式編程,不把SQL獨立放在xml文件了
- 省略Service,直接Controller調用DAO
Before
相信大家使用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) {
// 拋異常,或者做點其他事情
}
}
}
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 怎麼使用,可以看這裏:JAVA8之妙用Optional解決判斷Null爲空的問題
思考
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>