'How to append where clause to all queries that run with spring data MongoRepository?
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
