Mule-通过数据库连接器为 sql 查询创建动态 where 条件

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

我需要创建动态查询,其中 where 条件将根据进入 mule.The 的请求进行更改,请求将始终使用查询参数获取。下面是示例: http://localhost:8084/basePath?name=balwant&age=26http://localhost:8084/basePath?name=balwant&age=26&gender=M

同样会 dynamic.Now 我需要一种方法来创建一个查询,其中将根据请求中的查询参数添加 WHERE 条件。

还没有测试过这个,但是是这样的。检查 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]

如果消息入站属性中的值可用,则上述查询有效。但是如果你想用请求查询参数值构建你的 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]

我想到了使用自定义转换器。所以我为此使用了 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;
}}

现在这个returns 字符串类型的有效负载。

在数据库连接器中,select查询类型为动态。在 WHERE 条件后添加 #[payload].

干杯