Search code examples
jasper-reports

Can $X{} function used outside queryString?


I'm trying to use $X{} outside the queryString like this in jrxml

<parameter name="param_value" class="java.lang.String" isForPrompting="false">
    <defaultValueExpression><![CDATA[(" where $X{IN, country,country_param}")]]> </defaultValueExpression>
</parameter>

<queryString>
    <![CDATA[select user_id from user_profile $P{param_value}]]>
</queryString>

But I'm getting the error while evaluating param_value

Caused by: groovy.lang.MissingPropertyException: No such property: X for class:...

Can anyone tell me what's going wrong?


Solution

  • The short answer is no, the $X syntax only works inside of queryString.

    However, all JasperReports is doing when it encounters $X is to translate it into a string before running the query. So $X{IN, country,country_param} becomes country IN (country1, country2, ...)

    To solve your problem, you can generate the string yourself in Java and pass it to the report as a variable. Something like this:

    if(countryList == null){
        countryList = defaultCountryList;
    }
    
    StringBuilder whereParam = new StringBuilder();
    whereParam.append(country);
    whereParam.append("IN (");
    for(String s : countryList){
        whereParam.append("\""+s+"\"");
    }
    whereParam.append(")");
    
    reportParameters.setParameter("where_param", whereParam.toString());
    

    Then by using the $P! syntax you can place the string into the query. i.e:

    <queryString>
    <![CDATA[SELECT user_id FROM user_profile WHERE $P!{where_param}]]>
    </queryString>
    

    Unlike the $P syntax, $P! performs a simple string replacement before running the query, much like what $X is doing.