2015-10-16 39 views
1

我需要創建動態查詢,其中where條件將根據進入mule的請求進行更改。請求將始終通過查詢參數獲取。這裏有雲的例子: http://localhost:8084/basePath?name=balwant&age=26,OR http://localhost:8084/basePath?name=balwant&age=26&gender=MMule-Creating動態哪裏通過DB連接器進行sql查詢的條件

同樣這將是dynamic.Now我需要一個途徑,使我可以創造一個WHERE條件將基於請求中的查詢參數添加的查詢。

回答

0

我在使用「自定義變形金剛」的時候有過這樣的想法。所以我用這個java變壓器。

的邏輯看起來是這樣的:

public class QueryBuilder extends AbstractMessageTransformer { 

@Override 
public Object transformMessage(MuleMessage message, String outputEncoding) 
     throws TransformerException { 

    System.out.println("Query Params : " 
      + message.getInboundProperty("http.query.params").getClass() 
        .getName()); 

    Map<?, ?> map = message.getInboundProperty("http.query.params"); 

    System.out.println("Map keys : " + map.keySet()); 
    String where = ""; 
    for (Map.Entry<?, ?> entry : map.entrySet()) { 
     System.out.println(entry.getKey() + "/" + entry.getValue()); 
     where = where+" "+entry.getKey()+"="+"'"+entry.getValue()+"'"+" and"; 
    } 
    String whereCondition = where.substring(0, where.lastIndexOf(" ")); 
    System.out.println("Where condition is : "+ where.substring(0, where.lastIndexOf(" "))); 
    return whereCondition; 
}} 

現在這個返回它的有效載荷是字符串類型。

在數據庫連接器中,選擇查詢類型爲動態其中條件添加#[有效載荷]

乾杯

+0

使用動態查詢類型以這種方式添加WHERE條件是否安全? – mCeviker

2

沒有測試過這個,但是像這樣。檢查inboundProperty是存在的,編程建立查詢:

SELECT * FROM USERS WHERE NAME = '#[message.inboundProperties.name]' #[message.inboundProperties.gender !=null ? ' AND GENDER=' + message.inboundProperties.gender] #[message.inboundProperties.age !=null ? ' AND AGE=' + message.inboundProperties.age] 
+0

我需要它groovy –

+0

這不是你的問題。前提是通過inboundProperties查詢參數,並使用String連接構建查詢。 –

-1

上面的查詢工作,如果該值是在消息傳入可用屬性。但是如果你想用你的請求查詢參數值創建你的SQL查詢,那麼你需要像下面一樣使用(因爲查詢參數值將在來自mule 3.6.0以上的消息入站屬性http.query.param下可用)

SELECT * FROM USERS WHERE NAME = '#[message.inboundProperties.'http.query.params'.name]' #[message.inboundProperties.'http.query.params'.gender !=null ? ' AND GENDER=' + message.inboundProperties.'http.query.params'.gender] #[message.inboundProperties.'http.query.params'.age !=null ? ' AND AGE=' + message.inboundProperties.'http.query.params'.age]