JPA custom findOne and findAll

3.1k views Asked by At

I have a table place that contain as column "state" (it is an Enum that can be 'ACTIVE' or 'INACTIVE')

I would like to know if there is a way with JPA2 that when i call placeRepository.findAll() or placeRepository.getOne(id) only select the row in the database that are marked as "ACTIVE" ?

something like this

List<Place> findByStateActiveOnly();

EDIT: Bonus question: I'am at the moment refactoring my project to be able to add a place (and other entities) in a pending state. Because I have added an extra column "state" now i have to add to ALL my queries this condition "AND p.state=my.package.State.ACTIVE" like this;

@Query("select p from Place p where p.idPlace = ?1 AND p.state=my.package.State.ACTIVE") 

Isn't there a way to tell jpa to automatically select me if the state is ACTIVE ?

Thank you!

2

There are 2 answers

7
Predrag Maric On BEST ANSWER

With Hibernate, you can try annotating your entity with @Where, something like this

@Entity
@Where(clause = "state = 'ACTIVE'")
public class Place {...}
1
uaiHebert On

Do with parameter:

public interface YourRepository ... {
    List<Place> findByState(String state);
}

you will invoke like:

List<Place> placeList = youRepository.findByState("ACTIVE");