Spring-Data JPA CrudRepository returns Iterable, is it OK to cast this to List?

百般思念 提交于 2019-12-30 00:54:06

问题


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.

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?

Edit: 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?


回答1:


No, I don't think it's OK.

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.

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




回答2:


You mentioned [spring-data-jpa] so i guess you use JPA. In this case use JpaRepository instead of CrudRepository where the methods return List's like you want it.




回答3:


Your interface can still extends the CrudRepository, you can just add a new method findAll returning a list. Like example below:

@Repository
public interface DataRepository extends CrudRepository<Data, Long> {

    @Override
    List<Data> findAll();

}

If you have an "abstract" repository to be extended by all your repositories, you can add this method too, so it will has effect to all your repositories. Like example below:

@NoRepositoryBean
public interface GenericRepository<T> extends CrudRepository<T, Long> {

    @Override
    List<T> findAll();

}


来源:https://stackoverflow.com/questions/34702252/spring-data-jpa-crudrepository-returns-iterable-is-it-ok-to-cast-this-to-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!