Search code examples
javajpapredicate

JAVA JPA Predicate - Retrieve same column value in OR condition


I am trying to retrieve the data from Table TABLE_A, Table Table_A contain Column BB_NUM.

  • I need to write the expression in JPA BooleanExpression,

  • Needed to generate below SQL Query from JPA predicate logic:

    **Select * from TABLE_A where BB_NUM like 'GA22'OR BB_NUM like 'GA33';**
    
  • And this GA22 GA33 are comes dynamically, So this where condition is dynamically added.

  • Below code have write to dynamically create where condition in predicate expression, but this code is not working,

        boolean firstTime = true;
        str = "GA22GA33";
        BooleanExpression ent = null;
                        for (String array : str.split("GA")) {
                            if (StringUtils.isNotBlank(array)) {
                                if (firstTime) {
                                    ent = qTABLE_A.BB_NUM.containsIgnoreCase("GA" + array.trim());
                                    firstTime = false;
                                } else {
                                    ent.or(qTABLE_A.BB_NUM.containsIgnoreCase("GA" + array.trim()));
                                }
                            }
                        }
                        expressions.add(ent);
    

Above code is works like SQL,

**Select * from TABLE_A where BB_NUM like 'GA22';**

need to work

**Select * from TABLE_A where BB_NUM like 'GA22' or BB_NUM like 'GA33';**

Solution

  • Try it like:

    else {
        ent = ent.or(qTABLE_A.BB_NUM.containsIgnoreCase("GA" + array.trim()));
    }
    

    Also you can substitute if (firstTime) with if (ent == null)