gpt4 book ai didi

spring - 如何使用 Spring Data JPA 方法在 Kotlin 的 try-with-resources block 中返回 Stream?

转载 作者:行者123 更新时间:2023-12-02 12:39:58 24 4
gpt4 key购买 nike

所以我想创建一个 Spring BootSpring Data JPA项目使用 Kotlin假设我有一个 Person实体。让我们这样说:

@Entity
public class Person {

private @GeneratedValue @Id Long id;
private String name;

@OneToMany
private List<Person> friends;


}

我将创建以下界面以便能够使用 Try-with-ResourcesStream<Person> .
public interface PersonRepository extends Repository<Person, Long> {

@Query("select p from Person p")
Stream<Person> findAllStream();
}

所以通常在我的服务中,我会这样做:
@Service
class MyService {

@Autowired PersonRepository repository;

List<String> foo() {

try(Stream<Person> stream = repository.findAllStream()) {
return stream.flatMap(p -> p.getFriends().stream())
.map(f -> f.getName())
.collect(Collectors.toList());
}
}
}

现在,如果您想在 Kotlin 中执行此操作(IntelliJ 转换器不会生成有效代码)。我想你通常会做类似的事情:
class MyService @Autowired constructor(val personRepository: PersonRepository) {
fun foo() {
val list = personRepository.findAllStream()
.use {{p -> p.friends.stream()}.map {f -> f.name}}
}
}

只有你不能这样做,因为没有 #use流中的方法,您不能调用 #stream()来自 List .那么有没有办法做到这一点?

最佳答案

好吧,Kotlin 中的 Java 8 支持还没有完成。所以你可以像这样在你身边声明使用

inline fun <A : AutoCloseable, R> A.use(block: (A) -> R): R {
try {
return block(this)
} finally {
close()
}
}

另一种选择是直接在 Stream 上声明它。
inline fun <T, R> Stream<T>.use(block: (Stream<T>) -> R): R {
try {
return block(this)
} finally {
close()
}
}

更新

如果您是 Kotlin 的新手,您必须注意扩展是静态解析的:

Extensions do not actually modify classes they extend. By defining an extension, you do not insert new members into a class, but merely make new functions callable with the dot-notation on instances of this class.



查看更多 http://kotlinlang.org/docs/reference/extensions.html#extensions-are-resolved-statically

关于spring - 如何使用 Spring Data JPA 方法在 Kotlin 的 try-with-resources block 中返回 Stream?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35542972/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com