spring启动添加条件查询

rnmwe5a2  于 2021-07-23  发布在  Java
关注(0)|答案(2)|浏览(178)

当交易类型为rate$时,它不进行搜索/获取,但当交易类型为rate%时,它正在工作。

if(promotionInput.getDealType() != null) {
            query.addCriteria(Criteria.where(PromotionMasterConstants.DEAL_TYPE_DB).regex(promotionInput.getDealType(),"i"));
        }

我没有得到错误。

mbyulnm0

mbyulnm01#

您正在提供正则表达式模式( promotionInput.getDealType() 在本例中)而不转义特殊正则表达式字符。
特殊正则表达式元字符: ., +, *, ?, ^, $, (, ), [, ], {, }, |, \. 在你的情况下, promotionInput.getDealType() 包含未转义的美元符号,在提供正则表达式搜索之前应该转义。
如果美元符号($)位于整个正则表达式的末尾,则它与行的末尾匹配。
如果整个正则表达式由插入符号和美元符号(^如$)括起来,则它与整行匹配。

if(promotionInput.getDealType() != null) {

   // maybe check for other metacharacters?
   String escapedDealType = promotionInput.getDealType().replace("$", "\\$");

   query.addCriteria(Criteria.where(PromotionMasterConstants.DEAL_TYPE_DB)
                    .regex(escapedDealType,"i"));
}

mongodb中的数据

rs0:PRIMARY> db.promotion.find()
        { "_id" : ObjectId("6034bbfee56ebe09e8821e44"), "value" : "Rate $", "_class" : "com.xyz.model.Promotion" }
        { "_id" : ObjectId("6034bbfee56ebe09e8821e45"), "value" : "Rate %", "_class" : "com.xyz.model.Promotion" }

测试:用regex搜索值

测试已成功执行且呈绿色。

@Test
    public void name() {

        // drop everything
        mongoTemplate.dropCollection(Promotion.class);

        // persist entity with value field equls to "Rate $"
        final Promotion promotion = new Promotion();
        promotion.setValue("Rate $");
        mongoTemplate.insert(promotion);

        // persist entity with value field equls to "Rate %"
        final Promotion promotion2 = new Promotion();
        promotion2.setValue("Rate %");
        mongoTemplate.insert(promotion2);

        // RETURNS EMPTY COLLECTION
        Query query = new Query();
        query.addCriteria(Criteria.where("value").regex("Rate $", "i"));
        List<Promotion> promotions = mongoTemplate.find(query, Promotion.class);
        assertThat(promotions.size(), is(0));

        // query with escaped $
        // FINDS THE RECORD SUCCESSFULLY
        Query query2 = new Query();
        query2.addCriteria(Criteria.where("value").regex("Rate \\$", "i"));
        promotions = mongoTemplate.find(query2, Promotion.class);
        assertThat(promotions.size(), is(1));
        assertThat(promotions.get(0).getValue(), is("Rate $"));
    }
9njqaruj

9njqaruj2#

if(promotioninput.getdealtype()!=(空){
query.addcriteria(criteria.where(promotionmasterconstants.deal类型\u db).regex(promotioninput.getdealtype().replace(“$”,“$”,“i”));}
这得花点时间$

相关问题