How to replicate the Hibernate's @Where functi

2019-05-12 00:29发布

问题:

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?