Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data JPA - repository findAll method using flag column

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?

like image 719
elvisdorow Avatar asked Apr 02 '14 13:04

elvisdorow


People also ask

How does findAll work in JPA repository?

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.

Which is better CrudRepository or JpaRepository?

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.

What is the difference between findById and getById?

As a consequence, findById() returns the actual object and getById returns a reference of the entity.

What is difference between PagingAndSortingRepository and JpaRepository?

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.


1 Answers

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();


like image 81
Fabio Maffioletti Avatar answered Oct 24 '22 09:10

Fabio Maffioletti