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

查看:169
本文介绍了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,它有更流畅的处理空值的方法而不是可选。有谁知道如何将这种方法转换成这样的工作?

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?

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

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开始(到被释放), CrudRepository.findByIdOrNull(id:ID):T? = findById(id).orElse(null) Kotlin扩展现在提供了一种在Spring Data中检索可为空的实体的方法。

As of Spring Data Lovelace SR4 (to be released), 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> 包装器,请注意您还可以使用<$ c $创建自定义界面c> findFooById(id:ID):T?功能。查询执行是特定于商店的,但大多数都使用内部可为空的值,并且将避免可选< T> 包装器的成本。请注意,对于大多数用例,此开销应该可以忽略不计,因此建议使用内置扩展。

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 了解更多详情。

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

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