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更流畅.有人知道我该如何把这个方法转换成这样吗?

fun findById(id: ID): T?

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

推荐答案

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.

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.

See DATACMNS-1346 for more details.

Kotlin相关问答推荐

只能在元素区域中点击的Jetpack Compose列

调用即发即忘方法--哪个作用域?

某些公共函数显然不能在类实例上访问;Klaxon示例

为什么Kotlin协程程序即使有延迟也能输出?

在 Kotlin 中定义基于多态函数的泛型函数

当我通过媒体通知更改音乐时不要更新我的 UI

使用调度程序运行异步 Kotlin 代码

如何限制 Kotlin 中的枚举?

如何从 kotlin 函数中 Select 正确的枚举值

parallelStream()和asSequence().asStream().parallel()之间的区别

片段内的 Kotlin 按钮 onClickListener 事件

Kotlin内联扩展属性

Android Studio 和 Kotlin:Unresolved reference: also

从片段(fragment)中的点击事件启动协同程序

如何在Kotlin中创建无限长的序列

使用导航组件在不同的图形之间导航

接口中的属性不能有支持字段

Kotlin 与 C# 中的标志枚举变量具有相似效果的方式是什么

Failure delivering result on activity result

为什么在 Kotlin 中return可以返回一个return?