簡體   English   中英

Spring 開機添加條件查詢

[英]Spring boot add criteria query

當交易類型為費率 $ 時,它不會搜索/獲取,但當交易類型為費率 % 時,它正在工作。

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

我沒有收到錯誤。

您正在提供沒有 escaping 特殊正則表達式字符的正則表達式模式(在這種情況下為promotionInput.getDealType() )。

特殊的正則表達式元字符: ., +, *, ?, ^, $, (, ), [, ], {, }, |, \.

在您的情況下, promotionInput.getDealType()包含未轉義的美元符號,您應該在提供正則表達式搜索之前對其進行轉義。

如果美元符號 ($) 位於整個正則表達式的末尾,則它匹配行尾。

如果整個正則表達式由插入符號和美元符號(^like this$)括起來,它匹配整行。

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" }

測試:使用正則表達式搜索值

測試已成功執行並呈綠色。

@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 $"));
    }

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

query.addCriteria(Criteria.where(PromotionMasterConstants.DEAL_TYPE_DB).regex(promotionInput.getDealType().replace("$", "\$"),"i")); }

這將需要費率 $

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM