Spring Data JPA 如何使用 Kotlin nulls 而不是 Optional [英] Spring Data JPA How to use Kotlin nulls instead of Optional

查看:22
本文介绍了Spring Data JPA 如何使用 Kotlin nulls 而不是 Optional的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 Spring Data JPA 和 Kotlin 编写一个 Spring Boot 应用程序,我注意到在 CrudRepository 中有以下方法:

I'm writing a Spring Boot app with Spring Data JPA and Kotlin, and I've noticed that in CrudRepository there is the following method:

Optional<T> findById(ID id);

不过,我使用的是 Kotlin,它比 Optional 具有更流畅的处理空值的方式.有谁知道我将如何将该方法转换为这样的工作?

I'm using Kotlin, though, which has much more fluent ways of dealing with nulls than Optional. Does anyone know how I would convert that method to work like this?

fun findById(id: ID): T?

当我扩展 Repository 本身并使用该签名创建一个存储库时,我收到错误:

When I extend Repository itself and create a repo with that signature I get the error:

java.lang.ClassCastException: java.util.Optional cannot be cast to com.books.Book

推荐答案

从 Spring Data Lovelace SR4/Spring Boot 2.1.2 开始,一个 CrudRepository.findByIdOrNull(id: ID): T?= findById(id).orElse(null) Kotlin 扩展现在提供了一种开箱即用的方法来检索 Spring Data 中的可为空实体.

As of Spring Data Lovelace SR4 / Spring Boot 2.1.2, a CrudRepository.findByIdOrNull(id: ID): T? = findById(id).orElse(null) Kotlin extension now provides out of the box a way to retrieve nullable entities in Spring Data.

如果出于性能原因您想避免使用 Optional<T> 包装器,请注意您还可以使用 findFooById(id:ID): T? 函数.查询执行是特定于存储的,但大多数都使用内部可空值,并且将避免 Optional 包装器的成本.请注意,对于大多数用例,此开销应该可以忽略不计,因此建议使用内置扩展.

If for performance reasons you would like to avoid the usage of Optional<T> wrapper, be aware that you have also the possibility to create a custom interface with a findFooById(id: ID): T? function. Query execution is store specific, but and most are using internally nullable values and will avoid the cost of Optional<T> wrapper. Notice this overhead should be negligible for most use cases, so using the builtin extension is recommended method.

有关详细信息,请参阅 DATACMNS-1346.

See DATACMNS-1346 for more details.

这篇关于Spring Data JPA 如何使用 Kotlin nulls 而不是 Optional的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆