Thursday, March 26, 2015

Fast build where clause

To fast your code production it will be a good idea to write the common code to be general one then you can use it when you need without write and test it from beginning.
We want to build dynamic where clause at run-time in a general way.
Building where clause is included in cases like printing  jasper report or making a custom search form.

The basic structure of where clause is :
COLUMN_NAME Operator  Value1

Eg.
EMPLOYEES.EMP_NO = 5
EMPLOYEES.EMP_NAME likes '%Mahmoud%'
EMPLOYEES.HireDate between 1/1/2011 and 1/1/2015

"concatenateWhereClause" is a method that perform previous structure:
 public void concatenateWhereClause(StringBuilder where, String attr, String operator, String... value) {

        if (where.length() > 0) {

            where.append(" and ");

        }

        if (operator.trim().equals("like")) {

            where.append(attr + " like '%" + value[0] + "%'" + " ");

        } else if (operator.trim().equals("between")) {

            where.append(" " + attr + " between " + value[0] + " and " + value[1] + " ");

        } else {

            where.append(" " + attr + " " + operator + " " + value[0] + " ");

        }

    }

and you can call previous method in your search method:
 StringBuilder whereClause;
 public String startSearch() {

        ViewObject vo = ADFUtils.findIterator("VIEW_ITERATOR").getViewObject();

        whereClause = new StringBuilder("");

        if (SEARCH_COMPONENT.getValue() != null && !SEARCH_COMPONENT.getValue().toString().trim().equals("") ) {

            concatenateWhereClause(whereClause, "EMP_NO", "=", SEARCH_COMPONENT.getValue().toString());

        }

No comments:

Post a Comment

java - fill distinct objects in ArrayList

If you have a list that contains some objects that it is considered as duplication when two or three fields of these objects are equal. How ...