Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add global where clause for all find methods of Spring data JPA with Hibernate?

We are working on web application using Spring data JPA with hibernate.

In the application there is a field of compid in each entity. Which means in every DB call (Spring Data methods) will have to be checked with the compid.

I need a way that, this "where compid = ?" check to be injected automatically for every find method. So that we won't have to specifically bother about compid checks.

Is this possible to achieve from Spring Data JPA framework?

like image 749
Zeeshan Avatar asked Aug 30 '17 05:08

Zeeshan


People also ask

Can we use Spring data JPA and Hibernate together?

You cant actually use both of them in the same application.

Which method is used to fetch all rows in Spring data JPA repository?

I can use the findAll() method to select * from my_table to get all columns and rows.

What is the method name to fetch all data for a entity from database in repository class?

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.

What are the valid methods supported by Spring data JPA?

Spring Data JPA supports find, read, query, count and get.


1 Answers

Maybe Hibernate‘s annotation @Where will help you. It adds the passed condition to any JPA queries related to the entity. For example

@Entity
@Where(clause = "isDeleted='false'")
public class Customer {
    //...
    @Column
    private Boolean isDeleted;
}

More info: 1, 2

like image 61
Cepr0 Avatar answered Nov 15 '22 03:11

Cepr0