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
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]
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]
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