Spring-Data JPA CrudRepository返回Iterable,可以将其强制转换为List吗? [英] Spring-Data JPA CrudRepository returns Iterable, is it OK to cast this to List?

查看:523
本文介绍了Spring-Data JPA CrudRepository返回Iterable,可以将其强制转换为List吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个代码生成工具,以使用Spring-Data-Jpa为Spring-boot应用程序生成后端接线代码,这让我有点烦恼,CrudRepository中的方法返回Iterable而不是List,因为iterable不会提供足够的功能,但是List提供了足够的功能,因此我正在寻找将可迭代对象转换为列表的最佳方法.

I'm writing a code-gen tool to generate backend wiring code for Spring-boot applications using Spring-Data-Jpa and it's mildly annoying me that the methods in the CrudRepository return Iterable rather than List, as iterable doesn't provide quite enough functionality, but List does, so I'm looking for the best way to convert the iterable into a list.

我看到了这篇文章关于将可迭代项更改为集合我想知道,为什么不将其转换为List,而不是使用Guava之类的库或实现自己的函数来进行转换?这样做有什么我不知道的错误吗?

I saw this post on changing an iterable to a collection and I was wondering, rather than using a library like Guava or implementing my own function to do the conversion, why not just cast it to List? Is there something wrong with doing that that I don't know about?

我问,因为它是一种代码生成工具,因此使其生成会引入对第三方库的依赖关系的代码是不合理的,并且编写自己的函数进行转换也不是很合理,因为它必须位于某个地方,我宁愿不要在生成的代码中使用它.如果有点丑陋,可以进行简单的转换,但只是想知道我是否缺少某些内容?

I ask because since it's a code-gen tool it's not reasonable to make it generate code that introduces dependencies on 3rd party libraries, and writing my own function to do the conversion also isn't really reasonable because it would have to live somewhere and I'd rather not have that in the generated code. A simple cast will work, if a little ugly, but just wondered if there's something I'm missing?

推荐答案

不,我认为还可以.

虽然保证ListIterable,但Iterable可能不是List.这意味着,如果将Iterable强制转换为List,则在运行时可能会失败.即使可以使用,也不能保证它将来会继续使用,因为它可以在新版本的Spring Data JPA中进行更改而不会违反接口的约定.

While a List is guaranteed to be an Iterable an Iterable may not be a List. This means that if you do cast an Iterable to a List it may fail at runtime. Even if it works, there's no guarantee that it will continue to work in the future as it could change in new versions of Spring Data JPA without breaking the interface's contract.

您应该声明自己的返回List的查询方法,而不是使用强制转换.

Instead of using a cast, you should declare your own query methods that return List.

这篇关于Spring-Data JPA CrudRepository返回Iterable,可以将其强制转换为List吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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