Mybatis 3.5新特性-Optional支持

原文链接: http://www.itmuch.com/other/mybatis-optional-support/

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>

猜你喜欢

转载自blog.csdn.net/qq_34845394/article/details/100532507