I want to use the method findAll in a repository, but I`d like it to return just entities which have a certain value. For example, I want it to return just entities which are active = 1. Is there a way to do that?
Now I have to write for all my repositories something like this:
@Query("select p from Parameter p where p.active = 1")
public List<Parameter> findAll();
Instead of using the findOne method I have to write this in all my repositories:
@Query("select p from Parameter p where p.active = 1 and p.id=?1")
public Parameter findById(Long id);
Is there a better way to apply a blanket filter to all queries?
The Iterable<T> findAll() method returns all entities that are saved to the database. The T findOne(Long id) method returns the entity whose id is given as method parameter. If no entity is found, this method returns null.
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.
As a consequence, findById() returns the actual object and getById returns a reference of the entity.
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.
If you could consider moving from findAll to another strategy, look at the docs here http://docs.spring.io/spring-data/jpa/docs/1.5.1.RELEASE/reference/html/jpa.repositories.html#jpa.sample-app.finders.strategies
The JPA module supports defining a query manually as String or have it being derived from the method name.
So in your case if you want to retrieve all entities where active = 1, you can write something like:
public List<Parameter> findByActive(Integer active);
And you can also compose the method name in this way:
public Parameter findByIdAndActive(Long id, Integer active);
The translation between the method signature to the query to be executed is automatic.
Edit: If you are using boolean for active you can also have methods like
public List<Parameter> findByActiveTrue();
//or
public List<Parameter> findByActiveFalse();
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