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?
CrudRepository provides CRUD functions. PagingAndSortingRepository provides methods to do pagination and sort records. JpaRepository provides JPA related methods such as flushing the persistence context and delete records in a batch.
Crud Repository doesn't provide methods for implementing pagination and sorting. JpaRepository ties your repositories to the JPA persistence technology so it should be avoided. We should use CrudRepository or PagingAndSortingRepository depending on whether you need sorting and paging or not.
It is not thread safe by default, thus it needs to be managed (read: correctly bound to a thread and proxied to point to the thread-bound instance).
The CrudRepository interface declares many methods, but the methods that are relevant for this blog post are described in the following: The void delete(T entity) method deletes the entity whose id is given as a method parameter. The Iterable<T> findAll() method returns all entities that are saved to the database.
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.
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
.
Alternatively you may use Streamable.of(iterable).toList()
for doing the conversion. This answer also contains some background why Iterable
was chosen as the return type for these methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With