How to append where clause to all queries that run with spring data MongoRepository?
Asked Answered
H

0

4

I have entities that are persisted in MongoDB and use spring data MongoRepository to fetch data. Now i want to apply filter to all queries that executed on the entites, so i decided to use hibernate filter, something like this:

@Entity
@QueryEntity
@Document(collection = "Opportunity")
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@CompoundIndexes({
        @CompoundIndex(name = "productGroup_userId_uniqueness", def = "{'productGroupCode' : 1, 'userId': 1}", unique = true)
})
@FilterDef(name = "defaultFilter",parameters = @ParamDef(name = "unitCode",type = "string"))
@Filter(name = "defaultFilter" , condition = " unitCode like :unitCode")
public class Opportunity {

    @Id
    @Indexed
    private String id;

    @Indexed
    @Enumerated(EnumType.STRING)
    private OpportunityStatus opportunityStatus = OpportunityStatus.OPEN;

    private LeadType leadType;

    @Indexed
    private String userId;

    @Indexed
    private String productCode;

    @Indexed
    private String productGroupCode;

    @Indexed
    private Long actionId;

    private String assigneeId;

    @Transient
    private List<AbstractCommand> commandHistory = new ArrayList<>();

    @Transient
    private Map<Long, Boolean> actionStatus = new HashMap<>();
    
    private String unitCode;

}

and this is the repository class:

@Repository
public interface OpportunityRepository extends MongoRepository<Opportunity, String>, QuerydslPredicateExecutor<Opportunity> {
    // this repository contains more than 20 methods
    // and all of theme removed for question brevity
}

And I enabled hibernate filter on session with this way:

Session session = (entityManager).unwrap(Session.class);
session.enableFilter(filterName).setParameter("unitCode", this.getCurrentUserUnitCode());

Now, when I call OpportunityRepository.findAll(Predicate predicate, Pageable pageable) i expected to apply the defined filter on the entity, but it didn't work.

I think the reason is that MongoRepository hasn't any sense of hibernate @Filter and i should use another way to append where clause to all mongo queries that running on the Opportunity entity.

Homophonous answered 24/1, 2022 at 13:24 Comment(1)
Maybe hibernate OGM is usefullAmbivalence

© 2022 - 2024 — McMap. All rights reserved.