Mule-Creating dynamic where condition for sql query through DB connector

前端 未结 3 1258
终归单人心
终归单人心 2021-01-25 06:56

I need to create dynamic query wherein the where condition will be changed based on the request coming in to mule.The request will be always get with query parameter. Here goes

相关标签:
3条回答
  • 2021-01-25 07:11

    Above query works if the values are available in the message inbound properties. But if you want to build you SQL query with request query param values then you need to use like below (as the query param values will be available under message inbound properties http.query.param from mule 3.6.0 onward)

    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]
    
    0 讨论(0)
  • 2021-01-25 07:24

    Haven't tested this, but something like this. Check if the inboundProperty is there and build up the query programatically :

    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 讨论(0)
  • 2021-01-25 07:25

    I had this in my mind of using Custom Transformers. So I used java transformer for this.

    The logic looks something like this :

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

    Now this returns the payload which is string type.

    In DB connector, select Query type as Dynamic. After WHERE condition add #[payload].

    Cheers

    0 讨论(0)
提交回复
热议问题