54

我最喜欢的Mybatis 3.5新特性!超实用!

 4 years ago
source link: https://www.tuicool.com/articles/bieiUjV
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

作者:周立 来源:it牧场

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 怎么使用,本文不作赘述——JDK 12都发布了,你要我普及JDK 8的”新特性”吗?大家自行百度吧,百度很多了。关键词: Java 8 Optional

思考

Mybatis 已支持  OptionalMybatis 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。

balabala

Spring Data (jpa、redis、mongo…)花了很大力气重构(很多包名都换了,API名称也改了),率先支持了  Optional ,不得不说,在Java世界,  Spring 确实走在前面,引领着Java圈子的潮流。

uuaMFvM.jpg!web

Ubu2Yvz.gif

BryIFj2.jpg!web


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK