6
votes

One of our entities is defined using the @Where annotation to handle "soft-deletes".

@Entity
@Where(clause="user_type_cd != 'X'")
public class User {
...

Now, we are realizing that at times, we still want to find such entities. Unfortunately, the @Where annotation is working as designed and so the finders we have defined in JPARepository do not work to find deleted Users.

For example,

@Repository("userRepo")
public interface UserRepository extends JpaRepository<User, Long> {
    User findByLoginId(String login);
}

If the user has been deleted, then the findByLoginIs() method will not return a user if user_type_cd equals to 'X'.

However, at times, we still want to find such a user, so I was thinking of moving the

@Where(clause="user_type_cd != 'X'")

annotation from the entity into the repository. This way, I don't have to update all the methods in the repository and it would automatically add this criterium to all the finders. Then, I can create another repository which will find ALL the Users without regard to soft deletes.

However, I am not able to figure out the exact method that I can use to make all of the finders automatically append the

clause="user_type_cd != 'X'"

criteria to all methods of the repository without me having to explicitly write a custom @Query("... and user_type_cd != 'X'") for each finder method.

So, in short, I am looking for all the auto-generated findBy and such methods to append the user_type_cd != 'X' to each find that is generated.

Any ideas on how to accomplish this without resorting to custom @Query annotation?

1
FWIW @Where is nothing to do with JPA API. Perhaps you mean to tag this as Hibernate - Neil Stockton
Well, I am looking to replicate the behavior of the @Where using Spring Data JPA Repository. In other words, my Repository has quite a bit of finder methods in it, and I want them all to append this chunk of criteria to every finder query that they do. So in my mind, it's less of a hibernate specific thing and more of how do I get this done with Spring Data JPA. - Alex Paransky

1 Answers

-1
votes

I believe what you are looking for is one of either:

  1. Spring data jpa specifications, or
  2. Querydsl

There's a wealth of information with a simple google search on either. Here's a useful spring.io blog with details on both, and how to use them with a JpaRepository.