Fixes issue 41942: Apply new HQL Style to platform classes
authorCristian Berner <cristian.berner@openbravo.com>
Tue, 08 Oct 2019 11:48:18 +0200
changeset 36842 c47b63fff577
parent 36841 f20c0d75e5e4
child 36843 5a438a7a4de3
Fixes issue 41942: Apply new HQL Style to platform classes

StringBuffers and StringBuilders have been changed to String.
Some queries have been modified to use PreparedStatement, as this is not
prone to SQL Injection.
Some dynamic HQL queries have been modified to remove possible injections. Behaviour is the same as before.

Some refactoring was made in older classes.
New HQL convention has been applied to all modified classes.
modules/org.openbravo.client.application/src/org/openbravo/client/application/ParametersActionHandler.java
modules/org.openbravo.client.application/src/org/openbravo/client/application/attachment/AttachmentUtils.java
modules/org.openbravo.client.application/src/org/openbravo/client/application/event/AcctSchemaEventHandler.java
modules/org.openbravo.client.application/src/org/openbravo/client/application/navigationbarcomponents/RoleInfo.java
modules/org.openbravo.client.application/src/org/openbravo/client/application/navigationbarcomponents/UserInfoComponent.java
modules/org.openbravo.client.application/src/org/openbravo/client/application/personalization/PersonalizationActionHandler.java
modules/org.openbravo.client.application/src/org/openbravo/client/application/personalization/PersonalizationHandler.java
modules/org.openbravo.client.application/src/org/openbravo/client/application/window/ApplicationDictionaryCachedStructures.java
modules/org.openbravo.client.myob/src/org/openbravo/client/myob/MyOBUtils.java
modules/org.openbravo.client.myob/src/org/openbravo/client/myob/MyOpenbravoComponent.java
modules/org.openbravo.service.datasource/src/org/openbravo/service/datasource/HQLDataSourceService.java
modules/org.openbravo.service.datasource/src/org/openbravo/service/datasource/LinkToParentTreeDatasourceService.java
modules/org.openbravo.userinterface.selector/src/org/openbravo/userinterface/selector/CustomQuerySelectorDatasource.java
modules/org.openbravo.userinterface.selector/src/org/openbravo/userinterface/selector/model/domaintype/SelectorDomainType.java
src/org/openbravo/base/model/ModelProvider.java
src/org/openbravo/base/model/Property.java
src/org/openbravo/base/model/domaintype/TreeDomainType.java
src/org/openbravo/base/secureApp/DefaultValuesData.java
src/org/openbravo/base/secureApp/UserLock.java
src/org/openbravo/base/structure/BaseOBObject.java
src/org/openbravo/cluster/ClusterServiceManager.java
src/org/openbravo/dal/security/OrganizationStructureProvider.java
src/org/openbravo/dal/service/DataPoolChecker.java
src/org/openbravo/dal/service/OBQuery.java
src/org/openbravo/erpCommon/ad_forms/TranslationHandler.java
src/org/openbravo/erpCommon/ad_forms/TranslationManager.java
src/org/openbravo/erpCommon/ad_process/HeartbeatProcess.java
src/org/openbravo/erpCommon/businessUtility/Preferences.java
src/org/openbravo/erpCommon/obps/ActivationKey.java
src/org/openbravo/erpCommon/utility/SystemInfo.java
src/org/openbravo/erpCommon/utility/Utility.java
src/org/openbravo/service/dataset/DataSetService.java
src/org/openbravo/service/rest/DalWebService.java
--- a/modules/org.openbravo.client.application/src/org/openbravo/client/application/ParametersActionHandler.java	Wed Nov 20 17:29:27 2019 +0100
+++ b/modules/org.openbravo.client.application/src/org/openbravo/client/application/ParametersActionHandler.java	Tue Oct 08 11:48:18 2019 +0200
@@ -117,9 +117,9 @@
         ParameterValue value;
         OBQuery<ParameterValue> obq = OBDal.getInstance()
             .createQuery(ParameterValue.class,
-                dbFilterProperty + " = :filter and parameter = :param");
-        obq.setNamedParameter("filter", filterObject);
-        obq.setNamedParameter("param", param);
+                dbFilterProperty + " = :filter and parameter = :param")
+            .setNamedParameter("filter", filterObject)
+            .setNamedParameter("param", param);
 
         if (obq.count() == 0) {
           value = OBProvider.getInstance().get(ParameterValue.class);
--- a/modules/org.openbravo.client.application/src/org/openbravo/client/application/attachment/AttachmentUtils.java	Wed Nov 20 17:29:27 2019 +0100
+++ b/modules/org.openbravo.client.application/src/org/openbravo/client/application/attachment/AttachmentUtils.java	Tue Oct 08 11:48:18 2019 +0200
@@ -11,7 +11,7 @@
  * under the License.
  * The Original Code is Openbravo ERP.
  * The Initial Developer of the Original Code is Openbravo SLU
- * All portions are Copyright (C) 2015-2018 Openbravo SLU
+ * All portions are Copyright (C) 2015-2019 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -197,14 +197,17 @@
   }
 
   private static Date getLastUpdateOfAttachment(Attachment attachment) {
-    final StringBuilder hql = new StringBuilder();
-    hql.append("SELECT MAX(pv.updated) FROM OBUIAPP_ParameterValue pv");
-    hql.append(" WHERE pv.file.id =:fileId");
+    //@formatter:off
+    String hql = 
+            "select max(pv.updated) " +
+            "  from OBUIAPP_ParameterValue pv " +
+            " where pv.file.id = :fileId";
+    //@formatter:on
     final Query<Date> query = OBDal.getInstance()
         .getSession()
-        .createQuery(hql.toString(), Date.class);
-    query.setParameter("fileId", attachment.getId());
-    query.setMaxResults(1);
+        .createQuery(hql, Date.class)
+        .setParameter("fileId", attachment.getId())
+        .setMaxResults(1);
     Date metadataLastUpdate = query.uniqueResult();
     if (metadataLastUpdate == null || attachment.getUpdated().after(metadataLastUpdate)) {
       return attachment.getUpdated();
@@ -229,10 +232,16 @@
       throws OBException {
     Tab tab = adcs.getTab(tabId);
     Entity entity = ModelProvider.getInstance().getEntityByTableId(tab.getTable().getId());
-    final String hql = "SELECT a." + parameter.getPropertyPath() + " FROM " + entity.getName()
-        + " AS a WHERE a.id=:recordId";
-    final Query<Object> query = OBDal.getInstance().getSession().createQuery(hql, Object.class);
-    query.setParameter("recordId", recordId);
+    //@formatter:off
+    final String hql = 
+            "select a." + parameter.getPropertyPath() +
+            "  from " + entity.getName() + " as a " +
+            " where a.id=:recordId";
+    //@formatter:on
+    final Query<Object> query = OBDal.getInstance()
+        .getSession()
+        .createQuery(hql, Object.class)
+        .setParameter("recordId", recordId);
     try {
       return query.uniqueResult();
     } catch (Exception e) {
--- a/modules/org.openbravo.client.application/src/org/openbravo/client/application/event/AcctSchemaEventHandler.java	Wed Nov 20 17:29:27 2019 +0100
+++ b/modules/org.openbravo.client.application/src/org/openbravo/client/application/event/AcctSchemaEventHandler.java	Tue Oct 08 11:48:18 2019 +0200
@@ -135,19 +135,18 @@
   private void updateElementValues(String elementId, boolean assetPositive,
       boolean liabilityPositive, boolean ownersEquityPositive, boolean expensePositive,
       boolean revenuePositive) {
-    StringBuilder where = new StringBuilder();
     final String ACCOUNTSIGN_CREDIT = "C";
     final String ACCOUNTSIGN_DEBIT = "D";
     final String ACCOUNTTYPE_MEMO = "M";
     Element element = OBDal.getInstance().get(Element.class, elementId);
-    where.append(ElementValue.PROPERTY_ACCOUNTINGELEMENT + ".id = :element");
+    String where = "accountingElement.id = :element";
     OBQuery<ElementValue> elementValueQry = OBDal.getInstance()
-        .createQuery(ElementValue.class, where.toString());
-    elementValueQry.setFilterOnActive(false);
-    elementValueQry.setFilterOnReadableClients(false);
-    elementValueQry.setFilterOnReadableOrganization(false);
-    elementValueQry.setNamedParameter("element", element.getId());
-    elementValueQry.setFetchSize(1000);
+        .createQuery(ElementValue.class, where)
+        .setFilterOnActive(false)
+        .setFilterOnReadableClients(false)
+        .setFilterOnReadableOrganization(false)
+        .setNamedParameter("element", element.getId())
+        .setFetchSize(1000);
 
     ScrollableResults elementvalues = elementValueQry.scroll(ScrollMode.FORWARD_ONLY);
     try {
--- a/modules/org.openbravo.client.application/src/org/openbravo/client/application/navigationbarcomponents/RoleInfo.java	Wed Nov 20 17:29:27 2019 +0100
+++ b/modules/org.openbravo.client.application/src/org/openbravo/client/application/navigationbarcomponents/RoleInfo.java	Tue Oct 08 11:48:18 2019 +0200
@@ -11,7 +11,7 @@
  * under the License.
  * The Original Code is Openbravo ERP.
  * The Initial Developer of the Original Code is Openbravo SLU
- * All portions are Copyright (C) 2010-2018 Openbravo SLU
+ * All portions are Copyright (C) 2010-2019 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -84,13 +84,18 @@
     }
     roleOrganizations = new LinkedHashMap<>();
 
-    final StringBuilder hql = new StringBuilder();
-    hql.append("select ro.organization.id, ro.organization.name from ADRoleOrganization ro ");
-    hql.append("where ro.active=true and ro.role.id=:roleId and ro.organization.active=true ");
+    //@formatter:off
+    String hql = 
+            "select ro.organization.id, ro.organization.name " +
+            "  from ADRoleOrganization ro " +
+            " where ro.active=true" +
+            "   and ro.role.id=:roleId" +
+            "   and ro.organization.active=true ";
+    //@formatter:on
     Query<Object[]> roleOrgs = OBDal.getInstance()
         .getSession()
-        .createQuery(hql.toString(), Object[].class);
-    roleOrgs.setParameter("roleId", roleId);
+        .createQuery(hql, Object[].class)
+        .setParameter("roleId", roleId);
     for (Object[] orgInfo : roleOrgs.list()) {
       roleOrganizations.put((String) orgInfo[0], (String) orgInfo[1]);
     }
@@ -111,15 +116,20 @@
       organizationWarehouses.put(orgId, new ArrayList<RoleWarehouseInfo>());
     }
 
-    final StringBuilder hql = new StringBuilder();
-    hql.append("select w.id, w.name, w.organization.id from Warehouse w ");
-    hql.append(
-        "where w.active=true and w.organization.id in (:orgList) and w.client.id=:clientId and w.organization.active=true ");
+    //@formatter:off
+    String hql = 
+            "select w.id, w.name, w.organization.id " +
+            "  from Warehouse w " +
+            " where w.active=true" +
+            "   and w.organization.id in (:orgList)" +
+            "   and w.client.id=:clientId" +
+            "   and w.organization.active=true ";
+    //@formatter:on
     Query<Object[]> orgWarehouses = OBDal.getInstance()
         .getSession()
-        .createQuery(hql.toString(), Object[].class);
-    orgWarehouses.setParameterList("orgList", getOrganizations().keySet());
-    orgWarehouses.setParameter("clientId", clientId);
+        .createQuery(hql, Object[].class)
+        .setParameterList("orgList", getOrganizations().keySet())
+        .setParameter("clientId", clientId);
     for (Object[] entry : orgWarehouses.list()) {
       RoleWarehouseInfo warehouseInfo = new RoleWarehouseInfo(entry);
       for (Map.Entry<String, List<RoleWarehouseInfo>> ow : organizationWarehouses.entrySet()) {
--- a/modules/org.openbravo.client.application/src/org/openbravo/client/application/navigationbarcomponents/UserInfoComponent.java	Wed Nov 20 17:29:27 2019 +0100
+++ b/modules/org.openbravo.client.application/src/org/openbravo/client/application/navigationbarcomponents/UserInfoComponent.java	Tue Oct 08 11:48:18 2019 +0200
@@ -11,7 +11,7 @@
  * under the License.
  * The Original Code is Openbravo ERP.
  * The Initial Developer of the Original Code is Openbravo SLU
- * All portions are Copyright (C) 2010-2018 Openbravo SLU
+ * All portions are Copyright (C) 2010-2019 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -105,15 +105,19 @@
     }
 
     // return the complete role list for the current user
-    final StringBuilder hql = new StringBuilder();
-    hql.append(
-        "select ur.role.id, ur.role.name, ur.client.id, ur.client.name from ADUserRoles ur ");
-    hql.append(
-        "where ur.active=true and ur.userContact.id=:userId and ur.role.active=true and ur.role.isrestrictbackend=false ");
+    //@formatter:off
+    String hql = 
+            "select ur.role.id, ur.role.name, ur.client.id, ur.client.name " +
+            "  from ADUserRoles ur " +
+            " where ur.active=true" +
+            "   and ur.userContact.id=:userId" +
+            "   and ur.role.active=true" +
+            "   and ur.role.isrestrictbackend=false ";
+    //@formatter:on
     Query<Object[]> rolesQry = OBDal.getInstance()
         .getSession()
-        .createQuery(hql.toString(), Object[].class);
-    rolesQry.setParameter("userId", OBContext.getOBContext().getUser().getId());
+        .createQuery(hql, Object[].class)
+        .setParameter("userId", OBContext.getOBContext().getUser().getId());
     for (Object[] entry : rolesQry.list()) {
       userRoles.add(new RoleInfo(entry));
     }
--- a/modules/org.openbravo.client.application/src/org/openbravo/client/application/personalization/PersonalizationActionHandler.java	Wed Nov 20 17:29:27 2019 +0100
+++ b/modules/org.openbravo.client.application/src/org/openbravo/client/application/personalization/PersonalizationActionHandler.java	Tue Oct 08 11:48:18 2019 +0200
@@ -11,14 +11,13 @@
  * under the License. 
  * The Original Code is Openbravo ERP. 
  * The Initial Developer of the Original Code is Openbravo SLU 
- * All portions are Copyright (C) 2011-2018 Openbravo SLU 
+ * All portions are Copyright (C) 2011-2019 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
  */
 package org.openbravo.client.application.personalization;
 
-import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 
@@ -95,24 +94,21 @@
         if (uiPersonalization != null) {
           // is null if already removed
           OBDal.getInstance().remove(uiPersonalization);
-        }
-
-        // Delete also all the preferences that has this uiPersonalization as the 'Default View'
-        Map<String, Object> params = new HashMap<>(2);
-        StringBuilder hql = new StringBuilder();
-        hql.append(" as p where ");
-        hql.append(" p.searchKey = :uiPersonalization ");
-        params.put("uiPersonalization", uiPersonalization);
-        hql.append(" and p.property = :property");
-        params.put("property", "OBUIAPP_DefaultSavedView");
-
-        OBQuery<Preference> qPref = OBDal.getInstance()
-            .createQuery(Preference.class, hql.toString());
-        qPref.setNamedParameters(params);
-        List<Preference> preferences = qPref.list();
-
-        for (Preference preference : preferences) {
-          OBDal.getInstance().remove(preference);
+          // Delete also all the preferences that has this uiPersonalization as the 'Default View'
+          //@formatter:off
+          String hql = 
+                  " as p " +
+                  "  where p.searchKey = :uiPersonalization " +
+                  "    and p.property = :property ";
+          //@formatter:on
+          OBQuery<Preference> qPref = OBDal.getInstance()
+              .createQuery(Preference.class, hql)
+              .setNamedParameter("uiPersonalization", uiPersonalization.getId())
+              .setNamedParameter("property", "OBUIAPP_DefaultSavedView");
+          List<Preference> preferences = qPref.list();
+          for (Preference preference : preferences) {
+            OBDal.getInstance().remove(preference);
+          }
         }
 
         return new JSONObject().put("result", "success");
@@ -150,7 +146,7 @@
             personalizationID, clientID, orgID, roleID, userID, tabId, windowId,
             (String) parameters.get(TARGET), data, saveAsNewPreference);
         final JSONObject result = new JSONObject();
-        result.put("personalizationId", uiPersonalization.getId());
+        result.put(PERSONALIZATIONID, uiPersonalization.getId());
         return result;
       } else if (action.equals(ACTION_FORM)) {
         viewFormComponent.setParameters(parameters);
--- a/modules/org.openbravo.client.application/src/org/openbravo/client/application/personalization/PersonalizationHandler.java	Wed Nov 20 17:29:27 2019 +0100
+++ b/modules/org.openbravo.client.application/src/org/openbravo/client/application/personalization/PersonalizationHandler.java	Tue Oct 08 11:48:18 2019 +0200
@@ -11,7 +11,7 @@
  * under the License. 
  * The Original Code is Openbravo ERP. 
  * The Initial Developer of the Original Code is Openbravo SLU 
- * All portions are Copyright (C) 2011-2018 Openbravo SLU 
+ * All portions are Copyright (C) 2011-2019 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -489,78 +489,79 @@
       String userId, String roleId, String tabId, String windowId, boolean exactMatch) {
 
     Map<String, Object> parameters = new HashMap<>();
-    StringBuilder hql = new StringBuilder();
-    hql.append(" as p ");
-    hql.append(" where ");
+    //@formatter:off
+    String hql = " as p " +
+            " where ";
+    //@formatter:on
     if (exactMatch) {
       if (clientId != null) {
-        hql.append(" p.visibleAtClient.id = :clientId ");
+        hql += " p.visibleAtClient.id = :clientId ";
         parameters.put("clientId", clientId);
       } else {
-        hql.append(" p.visibleAtClient is null");
+        hql += " p.visibleAtClient is null ";
       }
 
       if (orgId != null) {
-        hql.append(" and p.visibleAtOrganization.id = :orgId ");
+        hql += " and p.visibleAtOrganization.id = :orgId ";
         parameters.put("orgId", orgId);
       } else {
-        hql.append(" and p.visibleAtOrganization is null ");
+        hql += " and p.visibleAtOrganization is null ";
       }
 
       if (userId != null) {
-        hql.append(" and p.user.id = :userId ");
+        hql += " and p.user.id = :userId ";
         parameters.put("userId", userId);
       } else {
-        hql.append(" and p.user is null ");
+        hql += " and p.user is null ";
       }
 
       if (roleId != null) {
-        hql.append(" and p.visibleAtRole.id = :roleId ");
+        hql += " and p.visibleAtRole.id = :roleId ";
         parameters.put("roleId", roleId);
       } else {
-        hql.append(" and p.visibleAtRole is null");
+        hql += " and p.visibleAtRole is null ";
       }
     } else {
       if (clientId != null) {
-        hql.append(" (p.visibleAtClient.id = :clientId or ");
+        hql += " (p.visibleAtClient.id = :clientId or ";
         parameters.put("clientId", clientId);
       } else {
-        hql.append(" (");
+        hql += " (";
       }
-      hql.append(" coalesce(p.visibleAtClient, '0')='0') ");
+      hql += " coalesce(p.visibleAtClient, '0')='0') ";
 
       if (roleId != null) {
-        hql.append(" and   (p.visibleAtRole.id = :roleId or ");
+        hql += " and (p.visibleAtRole.id = :roleId or ";
         parameters.put("roleId", roleId);
       } else {
-        hql.append(" and (");
+        hql += " and (";
       }
-      hql.append(" p.visibleAtRole is null) ");
+      hql += " p.visibleAtRole is null) ";
 
       // note orgId != null is handled below
       if (orgId == null) {
-        hql.append(" and (coalesce(p.visibleAtOrganization, '0')='0'))");
+        hql += " and (coalesce(p.visibleAtOrganization, '0')='0'))";
       }
 
       if (userId != null) {
-        hql.append("  and (p.user.id = :userId or ");
+        hql += " and (p.user.id = :userId or ";
         parameters.put("userId", userId);
       } else {
-        hql.append(" and (");
+        hql += " and (";
       }
-      hql.append(" p.user is null) ");
+      hql += " p.user is null) ";
     }
 
     if (tabId != null) {
-      hql.append(" and  p.tab.id = :tabId ");
+      hql += " and p.tab.id = :tabId ";
       parameters.put("tabId", tabId);
     } else {
-      hql.append(" and  p.window.id = :windowId ");
+      hql += "and p.window.id = :windowId";
       parameters.put("windowId", windowId);
     }
 
     OBQuery<UIPersonalization> qPers = OBDal.getInstance()
-        .createQuery(UIPersonalization.class, hql.toString());
+        .createQuery(UIPersonalization.class, hql);
     qPers.setNamedParameters(parameters);
     List<UIPersonalization> personalizations = qPers.list();
 
--- a/modules/org.openbravo.client.application/src/org/openbravo/client/application/window/ApplicationDictionaryCachedStructures.java	Wed Nov 20 17:29:27 2019 +0100
+++ b/modules/org.openbravo.client.application/src/org/openbravo/client/application/window/ApplicationDictionaryCachedStructures.java	Tue Oct 08 11:48:18 2019 +0200
@@ -110,7 +110,12 @@
   }
 
   private Set<String> getModulesInDevelopment() {
-    final String query = "select m.id from ADModule m where m.inDevelopment=true";
+    //@formatter:off
+    final String query = 
+            "select m.id " +
+            "  from ADModule m " +
+            " where m.inDevelopment=true";
+    //@formatter:on
     final Query<String> indevelMods = OBDal.getInstance()
         .getSession()
         .createQuery(query, String.class);
@@ -468,17 +473,15 @@
     if (useCache() && attMethodMetadataMap.get(strMethodTab) != null) {
       return attMethodMetadataMap.get(strMethodTab);
     }
-
-    StringBuilder where = new StringBuilder();
-    where.append(Parameter.PROPERTY_ATTACHMENTMETHOD + ".id = :attMethod");
-    where.append(" and (" + Parameter.PROPERTY_TAB + " is null or " + Parameter.PROPERTY_TAB
-        + ".id = :tab)");
-    where.append(" order by CASE WHEN " + Parameter.PROPERTY_FIXED + " is true THEN 1 ELSE 2 END");
-    where.append(" , " + Parameter.PROPERTY_SEQUENCENUMBER);
+    //@formatter:off
+    String where = "attachmentMethod.id = :attMethod" +
+            "   and (tab is null or tab.id = :tab) " +
+            " order by case when fixed is true then 1 else 2 end , sequenceNumber";
+    //@formatter:on
     final OBQuery<Parameter> qryParams = OBDal.getInstance()
-        .createQuery(Parameter.class, where.toString());
-    qryParams.setNamedParameter("attMethod", strAttMethodId);
-    qryParams.setNamedParameter("tab", strTabId);
+        .createQuery(Parameter.class, where)
+        .setNamedParameter("attMethod", strAttMethodId)
+        .setNamedParameter("tab", strTabId);
     List<Parameter> metadatas = qryParams.list();
     for (Parameter metadata : metadatas) {
       initializeMetadata(metadata);
--- a/modules/org.openbravo.client.myob/src/org/openbravo/client/myob/MyOBUtils.java	Wed Nov 20 17:29:27 2019 +0100
+++ b/modules/org.openbravo.client.myob/src/org/openbravo/client/myob/MyOBUtils.java	Tue Oct 08 11:48:18 2019 +0200
@@ -11,7 +11,7 @@
  * under the License.
  * The Original Code is Openbravo ERP.
  * The Initial Developer of the Original Code is Openbravo SLU
- * All portions are Copyright (C) 2010-2018 Openbravo SLU
+ * All portions are Copyright (C) 2010-2019 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -298,15 +298,15 @@
   }
 
   List<String> getAnonymousAccessibleWidgetClassesFromDatabase() {
-    final StringBuilder hql = new StringBuilder();
-    hql.append("SELECT widgetClass.id ");
-    hql.append("FROM OBKMO_WidgetClass widgetClass ");
-    hql.append("WHERE widgetClass.allowAnonymousAccess IS true ");
-    hql.append("AND widgetClass.superclass IS false ");
-    hql.append("AND widgetClass.availableInWorkspace IS true");
-    Query<String> query = OBDal.getInstance()
-        .getSession()
-        .createQuery(hql.toString(), String.class);
+    //@formatter:off
+    String hql = 
+            "select widgetClass.id " +
+            "  from OBKMO_WidgetClass widgetClass " +
+            " where widgetClass.allowAnonymousAccess is true " +
+            "   and widgetClass.superclass is false " +
+            "   and widgetClass.availableInWorkspace is true";
+    //@formatter:on
+    Query<String> query = OBDal.getInstance().getSession().createQuery(hql, String.class);
     return query.list();
   }
 }
--- a/modules/org.openbravo.client.myob/src/org/openbravo/client/myob/MyOpenbravoComponent.java	Wed Nov 20 17:29:27 2019 +0100
+++ b/modules/org.openbravo.client.myob/src/org/openbravo/client/myob/MyOpenbravoComponent.java	Tue Oct 08 11:48:18 2019 +0200
@@ -138,17 +138,17 @@
   }
 
   private List<String> getAccessibleWidgetClassIds(String roleId, String additionalWhereClause) {
-    final StringBuilder hql = new StringBuilder();
-    hql.append("SELECT widgetClassAccess.widgetClass.id ");
-    hql.append("FROM OBKMO_WidgetClassAccess widgetClassAccess ");
-    hql.append("WHERE widgetClassAccess.role.id=:roleId ");
-    hql.append("AND widgetClassAccess.active=true ");
+    //@formatter:off
+    String hql = 
+            "select widgetClassAccess.widgetClass.id " +
+            "  from OBKMO_WidgetClassAccess widgetClassAccess " +
+            " where widgetClassAccess.role.id = :roleId " +
+            "   and widgetClassAccess.active=true ";
+    //@formatter:on
     if (!StringUtils.isEmpty(additionalWhereClause)) {
-      hql.append(additionalWhereClause);
+      hql += additionalWhereClause;
     }
-    Query<String> query = OBDal.getInstance()
-        .getSession()
-        .createQuery(hql.toString(), String.class);
+    Query<String> query = OBDal.getInstance().getSession().createQuery(hql, String.class);
     if (StringUtils.isEmpty(roleId)) {
       query.setParameter("roleId", OBContext.getOBContext().getRole().getId());
     } else {
--- a/modules/org.openbravo.service.datasource/src/org/openbravo/service/datasource/HQLDataSourceService.java	Wed Nov 20 17:29:27 2019 +0100
+++ b/modules/org.openbravo.service.datasource/src/org/openbravo/service/datasource/HQLDataSourceService.java	Tue Oct 08 11:48:18 2019 +0200
@@ -367,9 +367,9 @@
     log.debug("HQL query: {}", hqlQuery);
     Query<Tuple> query = OBDal.getInstance().getSession().createQuery(hqlQuery, Tuple.class);
 
-    StringBuilder paramsLog = new StringBuilder();
+    String paramsLog = "";
 
-    // sets the parameters of the query
+    // sets the named parameters of the query
     for (String key : queryNamedParameters.keySet()) {
       // Injection and transforms might have modified the query removing named parameters. Check
       // that key is still in the query.
@@ -381,11 +381,23 @@
           query.setParameter(key, parameter);
         }
         if (log.isDebugEnabled()) {
-          paramsLog.append("\n").append(key).append(": ").append(parameter);
+          paramsLog += "\n" + key + ": " + parameter;
         }
       }
     }
 
+    // Set the hql clientId and organization parameters of the query
+    Set<String> namedParameters = query.getParameterMetadata().getNamedParameterNames();
+    if (namedParameters.contains("clientId")) {
+      query.setParameter("clientId", parameters.get("clientId"));
+      parameters.remove("clientId");
+    }
+    if (namedParameters.contains("organizations")) {
+      query.setParameterList("organizations",
+          parameters.get("organizations").replaceAll("'", "").split(","));
+      parameters.remove("organizations");
+    }
+
     log.debug("  parameters:{}", paramsLog);
 
     OBContext.restorePreviousMode();
@@ -536,7 +548,7 @@
     if (whereClause.trim().isEmpty()) {
       return whereClause;
     }
-    String updatedWhereClause = whereClause.toString();
+    String updatedWhereClause = whereClause;
     Entity entity = ModelProvider.getInstance().getEntityByTableId(table.getId());
     for (Column column : table.getADColumnList()) {
       // look for the property name, replace it with the column alias
@@ -606,37 +618,34 @@
   private String addAdditionalFilters(Table table, String hqlQuery, String filterWhereClause,
       Map<String, String> parameters) {
     OBContext.setAdminMode(true);
-    StringBuilder additionalFilter = new StringBuilder();
     final String entityAlias = table.getEntityAlias();
 
     // replace the carriage returns and the tabulations with blanks
     String hqlQueryWithFilters = hqlQuery.replace("\n", " ").replace("\r", " ");
 
+    String additionalFilter = entityAlias + ".client.id in ('0', :clientId)";
     // client filter
-    additionalFilter.append(entityAlias + ".client.id in ('0', '")
-        .append(OBContext.getOBContext().getCurrentClient().getId())
-        .append("')");
+    parameters.put("clientId", OBContext.getOBContext().getCurrentClient().getId());
 
     // organization filter
     final String orgs = DataSourceUtils.getOrgs(parameters.get(JsonConstants.ORG_PARAMETER));
     if (StringUtils.isNotEmpty(orgs)) {
-      additionalFilter.append(AND);
-      additionalFilter.append(entityAlias + ".organization in (" + orgs + ")");
+      additionalFilter += AND + entityAlias + ".organization.id in ( :organizations )";
+      parameters.put("organizations", orgs);
     }
 
-    addFilterWhereClause(additionalFilter, filterWhereClause);
+    additionalFilter = addFilterWhereClause(additionalFilter, filterWhereClause);
 
     // the _where parameter contains the filter clause and the where clause defined at tab level
     String whereClauseParameter = parameters.get(JsonConstants.WHERE_AND_FILTER_CLAUSE);
     if (whereClauseParameter != null && !whereClauseParameter.trim().isEmpty()
         && !"null".equals(whereClauseParameter)) {
-      additionalFilter.append(AND + whereClauseParameter);
+      additionalFilter += AND + whereClauseParameter;
     }
 
     if (hqlQueryWithFilters.contains(ADDITIONAL_FILTERS)) {
       // replace @additional_filters@ with the actual hql filters
-      hqlQueryWithFilters = hqlQueryWithFilters.replace(ADDITIONAL_FILTERS,
-          additionalFilter.toString());
+      hqlQueryWithFilters = hqlQueryWithFilters.replace(ADDITIONAL_FILTERS, additionalFilter);
     } else {
       // adds the hql filters in the proper place at the end of the query
       String separator = null;
@@ -647,16 +656,18 @@
         // otherwise, append with 'where'
         separator = WHERE;
       }
-      hqlQueryWithFilters = hqlQueryWithFilters + separator + additionalFilter.toString();
+      hqlQueryWithFilters = hqlQueryWithFilters + separator + additionalFilter;
     }
     OBContext.restorePreviousMode();
     return hqlQueryWithFilters;
   }
 
-  private void addFilterWhereClause(StringBuilder additionalFilter, String filterWhereClause) {
+  private String addFilterWhereClause(String additionalFilter, String filterWhereClause) {
+    String filterWithWhereClause = additionalFilter;
     if (!filterWhereClause.trim().isEmpty()) {
-      additionalFilter.append(AND + removeLeadingWhere(filterWhereClause));
+      filterWithWhereClause += AND + removeLeadingWhere(filterWhereClause);
     }
+    return filterWithWhereClause;
   }
 
   private String removeLeadingWhere(String whereClause) {
--- a/modules/org.openbravo.service.datasource/src/org/openbravo/service/datasource/LinkToParentTreeDatasourceService.java	Wed Nov 20 17:29:27 2019 +0100
+++ b/modules/org.openbravo.service.datasource/src/org/openbravo/service/datasource/LinkToParentTreeDatasourceService.java	Tue Oct 08 11:48:18 2019 +0200
@@ -11,7 +11,7 @@
  * under the License.
  * The Original Code is Openbravo ERP.
  * The Initial Developer of the Original Code is Openbravo SLU
- * All portions are Copyright (C) 2013-2018 Openbravo SLU
+ * All portions are Copyright (C) 2013-2019 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -218,10 +218,12 @@
     Property linkToParentProperty = getLinkToParentProperty(tableTree);
     Property nodeIdProperty = getNodeIdProperty(tableTree);
     boolean isMultiParentTree = tableTree.isHasMultiparentNodes();
-
-    StringBuilder whereClause = new StringBuilder();
+    //@formatter:off
+    String whereClause = 
+            " as e " +
+            " where ";
+    //@formatter:on
     final Map<String, Object> queryParameters = new HashMap<>();
-    whereClause.append(" as e where ");
     String actualParentId = new String(parentId);
     if (isMultiParentTree) {
       // The ids of multi parent trees are formed by the concatenation of the ids of its parents,
@@ -235,30 +237,30 @@
     boolean allowNotApplyingWhereClauseToChildren = !tableTree.isApplyWhereClauseToChildNodes();
     if ((fetchRoot || !allowNotApplyingWhereClauseToChildren) && hqlWhereClause != null) {
       // Include the hql where clause for all root nodes and for child nodes only if it is required
-      whereClause.append("(" + hqlWhereClause + ") and ");
+      whereClause += "(" + hqlWhereClause + ") and ";
     }
 
     if (hqlWhereClauseRootNodes != null && fetchRoot) {
       // If we are fetching the root nodes and there is a defined hqlWhereClauseRootNodes, apply it
-      whereClause.append(" " + hqlWhereClauseRootNodes + " ");
+      whereClause += " " + hqlWhereClauseRootNodes + " ";
     } else {
-      whereClause.append(" e." + linkToParentProperty.getName());
+      whereClause += " e." + linkToParentProperty.getName();
       if (fetchRoot) {
-        whereClause.append(" is null ");
+        whereClause += " is null ";
       } else {
         if (!linkToParentProperty.isPrimitive()) {
-          whereClause.append(".id");
+          whereClause += ".id";
         }
-        whereClause.append(" = :parentId ");
+        whereClause += " = :parentId ";
         queryParameters.put("parentId", actualParentId);
       }
       if (tab != null && tab.getTabLevel() > 0) {
         // only try to add the parent tab criteria when the tab is not the header
-        addParentTabCriteria(whereClause, tab, parameters, queryParameters);
+        whereClause = addParentTabCriteria(whereClause, tab, parameters, queryParameters);
       }
     }
     final OBQuery<BaseOBObject> query = OBDal.getInstance()
-        .createQuery(entity.getName(), whereClause.toString());
+        .createQuery(entity.getName(), whereClause);
 
     query.setFilterOnActive(false);
     query.setNamedParameters(queryParameters);
@@ -331,8 +333,8 @@
   }
 
   /**
-   * Adds to the where clause the criteria to filter the rows that belong with the record selected
-   * in the parent tab
+   * Returns the where clause with the criteria to filter the rows that belong with the record
+   * selected in the parent tab added
    * 
    * @param whereClause
    *          current hql where clase
@@ -343,9 +345,11 @@
    * @param queryParameters
    *          the parameters of the where clause, where the id of the record selected in the parent
    *          tab will be included
+   * @return whereClause with criteria to filter added
    */
-  private void addParentTabCriteria(StringBuilder whereClause, Tab tab,
-      Map<String, String> parameters, Map<String, Object> queryParameters) {
+  private String addParentTabCriteria(String whereClause, Tab tab, Map<String, String> parameters,
+      Map<String, Object> queryParameters) {
+    String finalWhereClause = whereClause;
     Tab parentTab = KernelUtils.getInstance().getParentTab(tab);
     if (parentTab != null) {
       String parentPropertyName = ApplicationUtils.getParentProperty(tab, parentTab);
@@ -354,7 +358,7 @@
           JSONArray criteria = (JSONArray) JsonUtils.buildCriteria(parameters).get("criteria");
           String parentRecordId = getParentRecordIdFromCriteria(criteria, parentPropertyName);
           if (parentRecordId != null) {
-            whereClause.append(" and e." + parentPropertyName + ".id = :parentRecordId ");
+            finalWhereClause += " and e." + parentPropertyName + ".id = :parentRecordId ";
             queryParameters.put("parentRecordId", parentRecordId);
           }
         } catch (JSONException e) {
@@ -362,6 +366,7 @@
         }
       }
     }
+    return finalWhereClause;
   }
 
   @Override
@@ -417,17 +422,20 @@
     } else if (nodeId instanceof BaseOBObject) {
       nodeIdStr = ((BaseOBObject) nodeId).getId().toString();
     }
-    StringBuilder whereClause = new StringBuilder();
-    whereClause.append(" as e where e." + linkToParentProperty.getName());
+    //@formatter:off
+    String whereClause = 
+            " as e " +
+            " where e." + linkToParentProperty.getName();
+    //@formatter:on
     if (!linkToParentProperty.isPrimitive()) {
-      whereClause.append(".id");
+      whereClause += ".id";
     }
-    whereClause.append(" = :nodeId ");
+    whereClause += " = :nodeId ";
     if (hqlWhereClause != null) {
-      whereClause.append(" and " + hqlWhereClause);
+      whereClause += " and " + hqlWhereClause;
     }
     final OBQuery<BaseOBObject> query = OBDal.getInstance()
-        .createQuery(entity.getName(), whereClause.toString());
+        .createQuery(entity.getName(), whereClause);
     query.setFilterOnActive(false);
 
     final Map<String, Object> parameters = new HashMap<>(1);
@@ -511,14 +519,15 @@
     Entity entity = ModelProvider.getInstance().getEntityByTableId(table.getId());
     Property nodeIdProperty = getNodeIdProperty(tableTree);
 
-    StringBuilder whereClause = new StringBuilder();
-    whereClause.append(" where " + nodeIdProperty.getName());
+    //@formatter:off
+    String whereClause = " where " + nodeIdProperty.getName();
+    //@formatter:on
     if (!nodeIdProperty.isPrimitive()) {
-      whereClause.append(".id");
+      whereClause += ".id";
     }
-    whereClause.append(" = :nodeId ");
+    whereClause += " = :nodeId ";
     final OBQuery<BaseOBObject> query = OBDal.getInstance()
-        .createQuery(entity.getName(), whereClause.toString());
+        .createQuery(entity.getName(), whereClause);
 
     final Map<String, Object> queryParameters = new HashMap<>(1);
     queryParameters.put("nodeId", nodeId);
@@ -552,15 +561,18 @@
     Entity entity = ModelProvider.getInstance().getEntityByTableId(table.getId());
     Property nodeIdProperty = getNodeIdProperty(tableTree);
 
-    StringBuilder whereClause = new StringBuilder();
-    whereClause.append(" as e where e." + nodeIdProperty.getName());
+    //@formatter:off
+    String whereClause = 
+            " as e " +
+            " where e." + nodeIdProperty.getName();
+    //@formatter:on
     if (!nodeIdProperty.isPrimitive()) {
-      whereClause.append(".id");
+      whereClause += ".id";
     }
-    whereClause.append(" = :nodeId ");
-    whereClause.append(" and (" + hqlWhereClause + ")");
+    whereClause += " = :nodeId ";
+    whereClause += " and (" + hqlWhereClause + ")";
     final OBQuery<BaseOBObject> query = OBDal.getInstance()
-        .createQuery(entity.getName(), whereClause.toString());
+        .createQuery(entity.getName(), whereClause);
 
     final Map<String, Object> queryParameters = new HashMap<>(1);
     queryParameters.put("nodeId", nodeId);
@@ -817,16 +829,18 @@
     Property linkToParentProperty = getLinkToParentProperty(tableTree);
     Property nodeIdProperty = getNodeIdProperty(tableTree);
 
-    StringBuilder whereClause = new StringBuilder();
-    whereClause.append(" as e where ");
-    whereClause.append(" e." + nodeIdProperty.getName());
+    //@formatter:off
+    String whereClause = 
+            " as e " +
+            " where e." + nodeIdProperty.getName();
+    //@formatter:on
     if (!nodeIdProperty.isPrimitive()) {
-      whereClause.append(".id");
+      whereClause += ".id";
     }
-    whereClause.append(" = :parentId ");
+    whereClause += " = :parentId ";
 
     final OBQuery<BaseOBObject> query = OBDal.getInstance()
-        .createQuery(entity.getName(), whereClause.toString());
+        .createQuery(entity.getName(), whereClause);
 
     final Map<String, Object> queryParameters = new HashMap<>();
     queryParameters.put("parentId", parentId);
--- a/modules/org.openbravo.userinterface.selector/src/org/openbravo/userinterface/selector/CustomQuerySelectorDatasource.java	Wed Nov 20 17:29:27 2019 +0100
+++ b/modules/org.openbravo.userinterface.selector/src/org/openbravo/userinterface/selector/CustomQuerySelectorDatasource.java	Tue Oct 08 11:48:18 2019 +0200
@@ -11,7 +11,7 @@
  * under the License.
  * The Original Code is Openbravo ERP.
  * The Initial Developer of the Original Code is Openbravo SLU
- * All portions are Copyright (C) 2011-2018 Openbravo SLU
+ * All portions are Copyright (C) 2011-2019 Openbravo SLU
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -69,8 +69,6 @@
 
   private static Logger log = LogManager.getLogger();
   private static final String ADDITIONAL_FILTERS = "@additional_filters@";
-  private static final String NEW_FILTER_CLAUSE = "\n AND ";
-  private static final String NEW_OR_FILTER_CLAUSE = "\n OR ";
   public static final String ALIAS_PREFIX = "alias_";
 
   @Override
@@ -87,6 +85,7 @@
     final SimpleDateFormat xmlDateTimeFormat = JsonUtils.createDateTimeFormat();
     final List<Map<String, Object>> result = new ArrayList<>();
     final List<Object> typedParameters = new ArrayList<>();
+    final Map<String, Object> namedParameters = new HashMap<>();
     // Defaulted to endRow + 2 to check for more records while scrolling.
     int totalRows = endRow + 2;
     int rowCount = 0;
@@ -108,13 +107,21 @@
       // cleared when number of records is big enough
       Hibernate.initialize(fields);
 
-      // Parse the HQL in case that optional filters are required
-      String HQL = parseOptionalFilters(parameters, sel, xmlDateFormat, typedParameters);
+      // Parse the hql in case that optional filters are required
+      String hql = parseOptionalFilters(parameters, sel, xmlDateFormat, typedParameters,
+          namedParameters);
 
       String sortBy = parameters.get("_sortBy");
-      HQL += getSortClause(sortBy, sel);
+      hql += getSortClause(sortBy, sel);
 
-      Query<Tuple> selQuery = OBDal.getInstance().getSession().createQuery(HQL, Tuple.class);
+      Query<Tuple> selQuery = OBDal.getInstance()
+          .getSession()
+          .createQuery(hql, Tuple.class);
+
+      selQuery.setParameterList("clients", (String[]) namedParameters.get("clients"));
+      if (namedParameters.containsKey("orgs")) {
+        selQuery.setParameterList("orgs", (String[]) namedParameters.get("orgs"));
+      }
 
       for (int i = 0; i < typedParameters.size(); i++) {
         selQuery.setParameter(ALIAS_PREFIX + Integer.toString(i), typedParameters.get(i));
@@ -186,18 +193,49 @@
 
   public String parseOptionalFilters(Map<String, String> parameters, Selector sel,
       SimpleDateFormat xmlDateFormat, List<Object> typedParameters) {
-    String HQL = sel.getHQL();
-    if (!HQL.contains(ADDITIONAL_FILTERS)) {
-      return HQL;
+    return parseOptionalFilters(parameters, sel, xmlDateFormat, typedParameters, new HashMap<>());
+  }
+
+  /**
+   * Returns the selectors HQL query. In case that it contains the '@additional_filters@' String it
+   * is replaced by a set of filter clauses.
+   *
+   * These include a filter clause:
+   * <ul>
+   * <li>for the main entity's client by the context's client.</li>
+   * <li>for the main entity's organization by an organization list see
+   * {@link DataSourceUtils#getOrgs(String)}</li>
+   * <li>with Selector's default filter expression.</li>
+   * <li>for each default expression defined on the selector fields.</li>
+   * <li>for each selector field in case exists a value for it on the parameters param.</li>
+   * </ul>
+   *
+   * @param parameters
+   *          Map of String values with the request parameters.
+   * @param sel
+   *          the selector that it is being retrieved the data.
+   * @param xmlDateFormat
+   *          SimpleDataFormat to be used to parse date Strings.
+   * @param typedParameters
+   *          Typed parameters to be used in the query
+   * @param namedParameters
+   *          Named parameters to be used in the query
+   * @return a String with the HQL to be executed.
+   */
+
+  public String parseOptionalFilters(Map<String, String> parameters, Selector sel,
+      SimpleDateFormat xmlDateFormat, List<Object> typedParameters,
+      Map<String, Object> namedParameters) {
+    String hql = sel.getHQL();
+    if (!hql.contains(ADDITIONAL_FILTERS)) {
+      return hql;
     }
     final String requestType = parameters.get(SelectorConstants.DS_REQUEST_TYPE_PARAMETER);
-    StringBuffer additionalFilter = new StringBuffer();
     final String entityAlias = sel.getEntityAlias();
     // Client filter
-    additionalFilter.append(entityAlias + ".client.id in ('0', '")
-        .append(OBContext.getOBContext().getCurrentClient().getId())
-        .append("')");
-
+    String additionalFilter = entityAlias + ".client.id in :clients";
+    final String[] clients = { "0", OBContext.getOBContext().getCurrentClient().getId() };
+    namedParameters.put("clients", clients);
     if (includeOrgFilter(parameters)) {
       // Organization filter
       boolean isOrgSelector = sel.getTable().getName().equals("Organization");
@@ -209,14 +247,18 @@
         orgs = DataSourceUtils.getOrgs(parameters.get(JsonConstants.ORG_PARAMETER));
       }
       if (StringUtils.isNotEmpty(orgs)) {
-        additionalFilter.append(NEW_FILTER_CLAUSE);
-        additionalFilter.append(entityAlias
-            + (isOrgSelector ? ".id in (" + orgs + ")" : ".organization in (" + orgs + ")"));
+        additionalFilter += " and " + entityAlias;
+        if (isOrgSelector) {
+          additionalFilter += ".id in :orgs";
+        } else {
+          additionalFilter += ".organization.id in :orgs";
+        }
+        namedParameters.put("orgs", orgs.replaceAll("'", "").split(","));
       }
     }
-    additionalFilter.append(getDefaultFilterExpression(sel, parameters));
+    additionalFilter += getDefaultFilterExpression(sel, parameters);
 
-    StringBuffer defaultExpressionsFilter = new StringBuffer();
+    String defaultExpressionsFilter = "";
     boolean hasFilter = false;
     List<SelectorField> fields = OBDao.getActiveOBObjectList(sel,
         Selector.PROPERTY_OBUISELSELECTORFIELDLIST);
@@ -250,9 +292,8 @@
             defaultValue = defaultValueObject.toString();
           }
           if (StringUtils.isNotEmpty(defaultValue)) {
-            defaultExpressionsFilter.append(NEW_FILTER_CLAUSE);
-            defaultExpressionsFilter.append(getWhereClause(operator, defaultValue, field,
-                xmlDateFormat, operatorvalue, typedParameters));
+            defaultExpressionsFilter += " and " + getWhereClause(operator, defaultValue, field,
+                xmlDateFormat, operatorvalue, typedParameters);
           }
         } catch (Exception e) {
           log.error("Error evaluating filter expression: " + e.getMessage(), e);
@@ -262,27 +303,26 @@
         String whereClause = getWhereClause(operator, value, field, xmlDateFormat, operatorvalue,
             typedParameters);
         if (!hasFilter) {
-          additionalFilter.append(NEW_FILTER_CLAUSE);
-          additionalFilter.append(" (");
+          additionalFilter += " and (";
           hasFilter = true;
         } else {
           if ("Window".equals(requestType)) {
-            additionalFilter.append(NEW_FILTER_CLAUSE);
+            additionalFilter += " and ";
           } else {
-            additionalFilter.append(NEW_OR_FILTER_CLAUSE);
+            additionalFilter += " or ";
           }
         }
-        additionalFilter.append(whereClause);
+        additionalFilter += whereClause;
       }
     }
     if (hasFilter) {
-      additionalFilter.append(")");
+      additionalFilter += ")";
     }
     if (defaultExpressionsFilter.length() > 0) {
-      additionalFilter.append(defaultExpressionsFilter);
+      additionalFilter += defaultExpressionsFilter;
     }
-    HQL = HQL.replace(ADDITIONAL_FILTERS, additionalFilter.toString());
-    return HQL;
+    hql = hql.replace(ADDITIONAL_FILTERS, additionalFilter);
+    return hql;
   }
 
   /**
@@ -512,7 +552,7 @@
       log.error("Error evaluating filter expression: " + e.getMessage(), e);
     }
     if (result != null && !result.toString().equals("")) {
-      return NEW_FILTER_CLAUSE + "(" + result.toString() + ")";
+      return " and " + "(" + result.toString() + ")";
     }
 
     return "";
--- a/modules/org.openbravo.userinterface.selector/src/org/openbravo/userinterface/selector/model/domaintype/SelectorDomainType.java	Wed Nov 20 17:29:27 2019 +0100
+++ b/modules/org.openbravo.userinterface.selector/src/org/openbravo/userinterface/selector/model/domaintype/SelectorDomainType.java	Tue Oct 08 11:48:18 2019 +0200
@@ -11,7 +11,7 @@
  * under the License. 
  * The Original Code is Openbravo ERP. 
  * The Initial Developer of the Original Code is Openbravo SLU 
- * All portions are Copyright (C) 2009-2018 Openbravo SLU 
+ * All portions are Copyright (C) 2009-2019 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -57,11 +57,14 @@
 
     Session session = ModelProvider.getInstance().getSession();
 
-    StringBuilder hql = new StringBuilder();
-    hql.append("SELECT s FROM " + SelectorDefinition.class.getName());
-    hql.append(" AS s WHERE s.referenceId = :referenceId");
-    Query<SelectorDefinition> query = session.createQuery(hql.toString(), SelectorDefinition.class);
-    query.setParameter("referenceId", getReference().getId());
+    //@formatter:off
+    String hql = 
+            "select s " +
+            "  from SelectorDefinition as s " +
+            " where s.referenceId = :referenceId";
+    //@formatter:on
+    Query<SelectorDefinition> query = session.createQuery(hql, SelectorDefinition.class)
+        .setParameter("referenceId", getReference().getId());
     final List<SelectorDefinition> list = query.list();
     if (list.isEmpty()) {
       // a base reference
@@ -98,12 +101,14 @@
   }
 
   private List<Column> readColumns(Session session, Table table) {
-    StringBuilder hql = new StringBuilder();
-    hql.append("SELECT c FROM " + Column.class.getName());
-    hql.append(" AS c WHERE c.table = :table");
-    hql.append(" ORDER BY c.position ASC");
-    Query<Column> query = session.createQuery(hql.toString(), Column.class);
-    query.setParameter("table", table);
+    //@formatter:off
+    String hql = 
+            "select c " +
+            "  from Column as c " +
+            " where c.table = :table " +
+            " order by c.position asc";
+    //@formatter:on
+    Query<Column> query = session.createQuery(hql, Column.class).setParameter("table", table);
     return query.list();
   }
 
--- a/src/org/openbravo/base/model/ModelProvider.java	Wed Nov 20 17:29:27 2019 +0100
+++ b/src/org/openbravo/base/model/ModelProvider.java	Tue Oct 08 11:48:18 2019 +0200
@@ -391,8 +391,13 @@
       connection = con.getConnection();
       PreparedStatement ps = null;
       try {
-        ps = connection.prepareStatement(
-            "select distinct model_impl from ad_reference where model_impl is not null");
+        //@formatter:off
+        String hql = 
+                "select distinct model_impl " +
+                "  from ad_reference " +
+                " where model_impl is not null";
+        //@formatter:on
+        ps = connection.prepareStatement(hql);
         ResultSet rs = ps.executeQuery();
         while (rs.next()) {
           String classname = rs.getString(1);
--- a/src/org/openbravo/base/model/Property.java	Wed Nov 20 17:29:27 2019 +0100
+++ b/src/org/openbravo/base/model/Property.java	Tue Oct 08 11:48:18 2019 +0200
@@ -24,6 +24,7 @@
 import java.util.Date;
 import java.util.List;
 import java.util.Set;
+import java.util.stream.Collectors;
 
 import org.apache.commons.lang.WordUtils;
 import org.apache.logging.log4j.LogManager;
@@ -968,14 +969,7 @@
    * @return a comma delimited list of allowed values, is used for enums.
    */
   public String concatenatedAllowedValues() {
-    final StringBuffer sb = new StringBuffer();
-    for (final String s : allowedValues) {
-      if (sb.length() > 0) {
-        sb.append(", ");
-      }
-      sb.append(s);
-    }
-    return sb.toString();
+    return allowedValues.stream().collect(Collectors.joining(", "));
   }
 
   /**
--- a/src/org/openbravo/base/model/domaintype/TreeDomainType.java	Wed Nov 20 17:29:27 2019 +0100
+++ b/src/org/openbravo/base/model/domaintype/TreeDomainType.java	Tue Oct 08 11:48:18 2019 +0200
@@ -11,7 +11,7 @@
  * under the License. 
  * The Original Code is Openbravo ERP. 
  * The Initial Developer of the Original Code is Openbravo SLU 
- * All portions are Copyright (C) 2013-2018 Openbravo SLU 
+ * All portions are Copyright (C) 2013-2019 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -53,11 +53,14 @@
 
     Session session = ModelProvider.getInstance().getSession();
 
-    StringBuilder hql = new StringBuilder();
-    hql.append("SELECT r FROM " + RefTree.class.getName());
-    hql.append(" AS r WHERE r.referenceId = :referenceId");
-    Query<RefTree> query = session.createQuery(hql.toString(), RefTree.class);
-    query.setParameter("referenceId", getReference().getId());
+    //@formatter:off
+    String hql = 
+            "select r " +
+            "  from RefTree as r " +
+            " where r.referenceId = :referenceId";
+    //@formatter:on
+    Query<RefTree> query = session.createQuery(hql, RefTree.class)
+        .setParameter("referenceId", getReference().getId());
     final List<RefTree> list = query.list();
     if (list.isEmpty()) {
       // a base reference
@@ -88,13 +91,15 @@
   }
 
   private Column readKeyColumn(Session session, Table table) {
-    StringBuilder hql = new StringBuilder();
-    hql.append("SELECT c FROM " + Column.class.getName());
-    hql.append(" AS c WHERE c.table = :table");
-    hql.append(" AND c.key = true");
-    hql.append(" ORDER BY c.position ASC");
-    Query<Column> query = session.createQuery(hql.toString(), Column.class);
-    query.setParameter("table", table);
+    //@formatter:off
+    String hql = 
+            "select c " +
+            "  from Column as c " +
+            " where c.table = :table " +
+            "   and c.key = true " +
+            " order by c.position asc";
+    //@formatter:on
+    Query<Column> query = session.createQuery(hql, Column.class).setParameter("table", table);
 
     List<Column> keyColumns = query.list();
     if (keyColumns.isEmpty()) {
--- a/src/org/openbravo/base/secureApp/DefaultValuesData.java	Wed Nov 20 17:29:27 2019 +0100
+++ b/src/org/openbravo/base/secureApp/DefaultValuesData.java	Tue Oct 08 11:48:18 2019 +0200
@@ -1,6 +1,6 @@
 /*
  ************************************************************************************
- * Copyright (C) 2001-2018 Openbravo S.L.U.
+ * Copyright (C) 2001-2019 Openbravo S.L.U.
  * Licensed under the Apache Software License version 2.0
  * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
  * Unless required by applicable law or agreed to  in writing,  software  distributed
@@ -11,9 +11,11 @@
  */
 package org.openbravo.base.secureApp;
 
+import java.sql.PreparedStatement;
 import java.sql.ResultSet;
 import java.sql.SQLException;
-import java.sql.Statement;
+import java.util.Arrays;
+import java.util.stream.Collectors;
 
 import javax.servlet.ServletException;
 
@@ -42,48 +44,66 @@
   /**
    * Select for relation
    */
-  public static String select(ConnectionProvider connectionProvider, String param1, String param2,
-      String param3, String param4) throws ServletException {
-    String strSql = "SELECT " + param1 + " AS COLUMNNAME";
-    strSql = strSql + " FROM " + param2 + " ";
-    strSql = strSql + " WHERE isActive = 'Y' ";
-    strSql = strSql + " AND isDefault = 'Y' ";
-    strSql = strSql + " AND AD_Client_ID IN (" + param3 + ") ";
-    strSql = strSql + " AND AD_Org_ID IN (" + param4 + ") ";
-    strSql = strSql + " ORDER BY AD_Client_ID";
+  public static String select(ConnectionProvider connectionProvider, String selArg, String table,
+      String clients, String orgs) throws ServletException {
 
-    Statement st = null;
-    ResultSet result;
+    //@formatter:off
+    String sql = 
+            "select " + selArg + " as COLUMNNAME " +
+            "  from " + table + " " +
+            " where isActive = 'Y' " +
+            "   and isDefault = 'Y' " +
+            "   and AD_Client_ID in " + parseIds(clients) +
+            "   and AD_Org_ID in " + parseIds(orgs) +
+            " order by AD_Client_ID";
+    //@formatter:on
+    ResultSet result = null;
     String resultado = "";
+    PreparedStatement st = null;
+    try {
+      st = connectionProvider.getPreparedStatement(sql);
 
-    try {
-      st = connectionProvider.getStatement();
-      result = st.executeQuery(strSql);
+      result = st.executeQuery();
 
       if (result.next()) {
         resultado = UtilSql.getValue(result, "COLUMNNAME");
       }
       result.close();
     } catch (SQLException e) {
-      log4j.error("SQL error in query: " + strSql + "Exception:" + e);
+      log4j.error("SQL error in query:{}", sql, e);
       throw new ServletException(
-          "@CODE=" + Integer.toString(e.getErrorCode()) + "@" + e.getMessage());
+          "@CODE=" + e.getErrorCode() + "@" + e.getMessage());
     } catch (NoConnectionAvailableException ec) {
-      log4j.error("Connection error in query: " + strSql + "Exception:" + ec);
+      log4j.error("Connection error in query:{}", sql, ec);
       throw new ServletException("@CODE=NoConnectionAvailable");
     } catch (PoolNotFoundException ep) {
-      log4j.error("Pool error in query: " + strSql + "Exception:" + ep);
+      log4j.error("Pool error in query:{}", sql, ep);
       throw new ServletException("@CODE=NoConnectionAvailable");
     } catch (Exception ex) {
-      log4j.error("Exception in query: " + strSql + "Exception:" + ex);
+      log4j.error("Exception in query:{}", sql, ex);
       throw new ServletException("@CODE=@" + ex.getMessage());
     } finally {
       try {
-        connectionProvider.releaseStatement(st);
-      } catch (Exception ignore) {
-        ignore.printStackTrace();
+        if (result != null) {
+          result.close();
+        }
+        connectionProvider.releasePreparedStatement(st);
+      } catch (Exception ex) {
+        log4j.error("Error releasing prepared statement:{}", sql, ex);
       }
     }
     return (resultado);
   }
+
+  /**
+   * Parses a list of parameters in the form "'id1','id2','id3'" to a string formatted for sql IN
+   * clause "('id1', 'id2', 'id3')"
+   * 
+   * @param parameters
+   *          String with parameters formatted like so "'id1', 'id2', 'id3'"
+   * @return Formatted parameter list for SQL IN clause: "('id1', 'id2', 'id3')"
+   */
+  private static String parseIds(String parameters) {
+    return Arrays.stream(parameters.split(",")).collect(Collectors.joining(",", "(", ")"));
+  }
 }
--- a/src/org/openbravo/base/secureApp/UserLock.java	Wed Nov 20 17:29:27 2019 +0100
+++ b/src/org/openbravo/base/secureApp/UserLock.java	Tue Oct 08 11:48:18 2019 +0200
@@ -11,7 +11,7 @@
  * under the License. 
  * The Original Code is Openbravo ERP. 
  * The Initial Developer of the Original Code is Openbravo SL 
- * All portions are Copyright (C) 2010-2018 Openbravo SL 
+ * All portions are Copyright (C) 2010-2019 Openbravo SL 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -101,13 +101,17 @@
 
     // to improve performance this query is not done as subquery of the main one,
     // see issue #25466
-    StringBuilder hql = new StringBuilder();
-    hql.append("select max(s1.creationDate)");
-    hql.append("  from ADSession s1");
-    hql.append(" where s1.username = :name");
-    hql.append("   and s1.loginStatus != 'F'");
-    Query<Date> q1 = OBDal.getInstance().getSession().createQuery(hql.toString(), Date.class);
-    q1.setParameter("name", userName);
+    //@formatter:off
+    String hql = 
+            "select max(s1.creationDate) " +
+            "  from ADSession s1 " +
+            " where s1.username = :name " +
+            "   and s1.loginStatus != 'F'";
+    //@formatter:on
+    Query<Date> q1 = OBDal.getInstance()
+        .getSession()
+        .createQuery(hql, Date.class)
+        .setParameter("name", userName);
     Date lastFailedAttempt = q1.list().get(0);
 
     if (lastFailedAttempt == null) {
@@ -118,16 +122,19 @@
     log4j.debug("Time taken to check user lock 1st query " + (System.currentTimeMillis() - t));
 
     long t1 = System.currentTimeMillis();
-    hql = new StringBuilder();
-    hql.append("select count(*)");
-    hql.append("  from ADSession s ");
-    hql.append(" where s.loginStatus='F'");
-    hql.append("   and s.username = :name");
-    hql.append("   and s.creationDate > :lastFail");
-
-    Query<Long> q = OBDal.getInstance().getSession().createQuery(hql.toString(), Long.class);
-    q.setParameter("name", userName);
-    q.setParameter("lastFail", lastFailedAttempt);
+    //@formatter:off
+    hql = 
+            "select count(*) " +
+            "  from ADSession s " +
+            " where s.loginStatus = 'F' " +
+            "   and s.username = :name " +
+            "   and s.creationDate > :lastFail";
+    //@formatter:on
+    Query<Long> q = OBDal.getInstance()
+        .getSession()
+        .createQuery(hql, Long.class)
+        .setParameter("name", userName)
+        .setParameter("lastFail", lastFailedAttempt);
 
     numberOfFails = q.list().get(0).intValue();
     log4j.debug("Time taken to check user lock " + (System.currentTimeMillis() - t)
--- a/src/org/openbravo/base/structure/BaseOBObject.java	Wed Nov 20 17:29:27 2019 +0100
+++ b/src/org/openbravo/base/structure/BaseOBObject.java	Tue Oct 08 11:48:18 2019 +0200
@@ -11,7 +11,7 @@
  * under the License. 
  * The Original Code is Openbravo ERP. 
  * The Initial Developer of the Original Code is Openbravo SLU 
- * All portions are Copyright (C) 2008-2018 Openbravo SLU 
+ * All portions are Copyright (C) 2008-2019 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -147,16 +147,19 @@
   }
 
   private BaseOBObject getTranslation(Property trlParentProperty, Language language, String id) {
-    StringBuilder hql = new StringBuilder();
-    hql.append("select trl from " + trlParentProperty.getEntity() + " as trl ");
-    hql.append("where trl." + trlParentProperty.getName() + ".id = :id ");
-    hql.append("and trl.language = :language and trl.active = true");
+    //@formatter:off
+    String hql = 
+            "select trl " +
+            "  from " + trlParentProperty.getEntity() + " as trl " +
+            " where trl." + trlParentProperty.getName() + ".id = :id " +
+            "   and trl.language = :language and trl.active = true";
+    //@formatter:on
     Query<BaseOBObject> query = OBDal.getInstance()
         .getSession()
-        .createQuery(hql.toString(), BaseOBObject.class);
-    query.setParameter("id", id);
-    query.setParameter("language", language);
-    query.setMaxResults(1);
+        .createQuery(hql, BaseOBObject.class)
+        .setParameter("id", id)
+        .setParameter("language", language)
+        .setMaxResults(1);
     return query.uniqueResult();
   }
 
--- a/src/org/openbravo/cluster/ClusterServiceManager.java	Wed Nov 20 17:29:27 2019 +0100
+++ b/src/org/openbravo/cluster/ClusterServiceManager.java	Tue Oct 08 11:48:18 2019 +0200
@@ -11,7 +11,7 @@
  * under the License. 
  * The Original Code is Openbravo ERP. 
  * The Initial Developer of the Original Code is Openbravo SLU 
- * All portions are Copyright (C) 2017-2018 Openbravo SLU
+ * All portions are Copyright (C) 2017-2019 Openbravo SLU
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -359,13 +359,18 @@
     }
 
     private void updateNodeOfService(String formerNodeId, String serviceName, Date now) {
-      StringBuilder hql = new StringBuilder();
-      hql.append("UPDATE ADClusterService ");
-      hql.append("SET nodeID = :newNodeId, nodeName = :newNodeName, updated = :updated ");
-      hql.append("WHERE service = :service AND nodeID = :formerNodeId");
+      //@formatter:off
+      String hql = 
+              "update ADClusterService " +
+              "  set nodeID = :newNodeId, " +
+              "      nodeName = :newNodeName," +
+              "      updated = :updated " +
+              " where service = :service " +
+              "   and nodeID = :formerNodeId";
+      //@formatter:on
       int rowCount = OBDal.getInstance()
           .getSession()
-          .createQuery(hql.toString()) //
+          .createQuery(hql) //
           .setParameter("newNodeId", manager.nodeId) //
           .setParameter("newNodeName", manager.nodeName) //
           .setParameter("updated", now) //
@@ -379,12 +384,16 @@
     }
 
     private void updateLastPing(String serviceName, Date now) {
-      StringBuilder hql = new StringBuilder();
-      hql.append("UPDATE ADClusterService SET updated = :updated ");
-      hql.append("WHERE service = :service AND nodeID = :currentNodeId");
+      //@formatter:off
+      String hql = 
+              "update ADClusterService " +
+              "  set updated = :updated " +
+              " where service = :service" +
+              "   and nodeID = :currentNodeId";
+      //@formatter:on
       OBDal.getInstance()
           .getSession()
-          .createQuery(hql.toString()) //
+          .createQuery(hql) //
           .setParameter("updated", now) //
           .setParameter("service", serviceName) //
           .setParameter("currentNodeId", manager.nodeId) //
--- a/src/org/openbravo/dal/security/OrganizationStructureProvider.java	Wed Nov 20 17:29:27 2019 +0100
+++ b/src/org/openbravo/dal/security/OrganizationStructureProvider.java	Tue Oct 08 11:48:18 2019 +0200
@@ -11,7 +11,7 @@
  * under the License. 
  * The Original Code is Openbravo ERP. 
  * The Initial Developer of the Original Code is Openbravo SLU 
- * All portions are Copyright (C) 2008-2018 Openbravo SLU 
+ * All portions are Copyright (C) 2008-2019 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -39,7 +39,6 @@
 import org.openbravo.dal.service.OBQuery;
 import org.openbravo.erpCommon.utility.StringCollectionUtils;
 import org.openbravo.model.common.enterprise.Organization;
-import org.openbravo.model.common.enterprise.OrganizationType;
 
 /**
  * Builds a tree of organizations to compute the accessible organizations for the current
@@ -81,15 +80,22 @@
     // Read all org tree of any client: bypass DAL to prevent security checks and Hibernate to make
     // it in a single query. Using direct SQL managed by Hibernate as in this point SQLC is not
     // allowed because this code is used while generating entities.
-    String sql = "select n.node_id, n.parent_id, o.isready, ot.islegalentity, ot.isbusinessunit, ot.istransactionsallowed, o.isperiodcontrolallowed"
-        + "  from ad_tree t, ad_treenode n, ad_org o, ad_orgtype ot"
-        + " where n.node_id = o.ad_org_id" + "   and o.ad_orgtype_id = ot.ad_orgtype_id"
-        + "   and n.ad_tree_id = t.ad_tree_id" + "   and t.ad_table_id = '155'"
-        + "   and t.ad_client_id = :clientId";
+    //@formatter:off
+    String sql = 
+            "select n.node_id, n.parent_id, o.isready, ot.islegalentity, ot.isbusinessunit, ot.istransactionsallowed, o.isperiodcontrolallowed" +
+            "  from ad_tree t, ad_treenode n, ad_org o, ad_orgtype ot" +
+            " where n.node_id = o.ad_org_id " +
+            "   and o.ad_orgtype_id = ot.ad_orgtype_id" +
+            "   and n.ad_tree_id = t.ad_tree_id" +
+            "   and t.ad_table_id = '155'" +
+            "   and t.ad_client_id = :clientId";
+    //@formatter:on
 
     @SuppressWarnings("rawtypes")
-    NativeQuery qry = OBDal.getInstance().getSession().createNativeQuery(sql);
-    qry.setParameter("clientId", getClientId());
+    NativeQuery qry = OBDal.getInstance()
+        .getSession()
+        .createNativeQuery(sql)
+        .setParameter("clientId", getClientId());
 
     @SuppressWarnings("unchecked")
     List<Object[]> treeNodes = qry.list();
@@ -313,16 +319,18 @@
    * Returns the legal entities of the selected client.
    */
   public List<Organization> getLegalEntitiesListForSelectedClient(String paramClientId) {
-    StringBuffer where = new StringBuffer();
-    where.append(" as org");
-    where.append(" join org." + Organization.PROPERTY_ORGANIZATIONTYPE + " as orgType");
-    where.append(" where org." + Organization.PROPERTY_CLIENT + ".id = :client");
-    where.append("   and orgType." + OrganizationType.PROPERTY_LEGALENTITY + " = true");
+    //@formatter:off
+    String where = 
+            " as org " +
+            "  join org.organizationType as orgType " +
+            " where org.client.id = :client " +
+            "   and orgType.legalEntity = true";
+    //@formatter:on
     OBQuery<Organization> orgQry = OBDal.getInstance()
-        .createQuery(Organization.class, where.toString());
-    orgQry.setFilterOnReadableClients(false);
-    orgQry.setFilterOnReadableOrganization(false);
-    orgQry.setNamedParameter("client", paramClientId);
+        .createQuery(Organization.class, where)
+        .setFilterOnReadableClients(false)
+        .setFilterOnReadableOrganization(false)
+        .setNamedParameter("client", paramClientId);
     return orgQry.list();
   }
 
--- a/src/org/openbravo/dal/service/DataPoolChecker.java	Wed Nov 20 17:29:27 2019 +0100
+++ b/src/org/openbravo/dal/service/DataPoolChecker.java	Tue Oct 08 11:48:18 2019 +0200
@@ -11,7 +11,7 @@
  * under the License.
  * The Original Code is Openbravo ERP.
  * The Initial Developer of the Original Code is Openbravo SLU
- * All portions are Copyright (C) 2018 Openbravo SLU
+ * All portions are Copyright (C) 2018-2019 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -77,13 +77,13 @@
    * @return a new Map object with the mapping (Report_ID, POOL)
    */
   private Map<String, String> findActiveDataPoolSelection() {
-    final StringBuilder hql = new StringBuilder();
-    hql.append("select dps.report.id, dps.dataPool from OBUIAPP_Data_Pool_Selection dps ");
-    hql.append("where dps.active = true");
-
-    Query<Object[]> query = OBDal.getInstance()
-        .getSession()
-        .createQuery(hql.toString(), Object[].class);
+    //@formatter:off
+    String hql = 
+            "select dps.report.id, dps.dataPool " +
+            "  from OBUIAPP_Data_Pool_Selection dps " +
+            " where dps.active = true";
+    //@formatter:on
+    Query<Object[]> query = OBDal.getInstance().getSession().createQuery(hql, Object[].class);
     List<Object[]> queryResults = query.list();
 
     Map<String, String> selection = new HashMap<>(queryResults.size());
@@ -94,14 +94,19 @@
   }
 
   private void refreshDefaultPoolPreference() {
-    final StringBuilder hql = new StringBuilder();
-    hql.append("select p.searchKey from ADPreference p ");
-    hql.append(
-        "where p.property='OBUIAPP_DefaultDBPoolForReports' and p.active=true and p.visibleAtClient.id='0' and p.visibleAtOrganization.id='0' ");
+    //@formatter:off
+    String hql = 
+            "select p.searchKey " +
+            "  from ADPreference p " +
+            " where p.property='OBUIAPP_DefaultDBPoolForReports' " +
+            "   and p.active = true " +
+            "   and p.visibleAtClient.id = '0' " +
+            "   and p.visibleAtOrganization.id = '0' ";
+    //@formatter:on
     Query<String> defaultPoolQuery = OBDal.getInstance()
         .getSession()
-        .createQuery(hql.toString(), String.class);
-    defaultPoolQuery.setMaxResults(1);
+        .createQuery(hql, String.class)
+        .setMaxResults(1);
     setDefaultReadOnlyPool(defaultPoolQuery.uniqueResult());
   }
 
--- a/src/org/openbravo/dal/service/OBQuery.java	Wed Nov 20 17:29:27 2019 +0100
+++ b/src/org/openbravo/dal/service/OBQuery.java	Tue Oct 08 11:48:18 2019 +0200
@@ -187,13 +187,13 @@
    * @return the row number or -1 if not found
    */
   public int getRowNumber(String targetId) {
-    String qryStr = createQueryString();
-    if (qryStr.toLowerCase().contains(FROM_SPACED)) {
-      final int index = qryStr.indexOf(FROM_SPACED) + FROM_SPACED.length();
-      qryStr = qryStr.substring(index);
+    String sql = createQueryString();
+    if (sql.toLowerCase().contains(FROM_SPACED)) {
+      final int index = sql.indexOf(FROM_SPACED) + FROM_SPACED.length();
+      sql = sql.substring(index);
     }
-    final Query<String> qry = getSession()
-        .createQuery("select " + usedAlias + "id " + FROM_SPACED + qryStr, String.class);
+    sql = "select " + usedAlias + "id " + FROM_SPACED + sql;
+    final Query<String> qry = getSession().createQuery(sql, String.class);
     setParameters(qry);
 
     try (ScrollableResults results = qry.scroll(ScrollMode.FORWARD_ONLY)) {
--- a/src/org/openbravo/erpCommon/ad_forms/TranslationHandler.java	Wed Nov 20 17:29:27 2019 +0100
+++ b/src/org/openbravo/erpCommon/ad_forms/TranslationHandler.java	Tue Oct 08 11:48:18 2019 +0200
@@ -10,13 +10,17 @@
  * Portions created by Jorg Janke are Copyright (C) 1999-2001 Jorg Janke, parts
  * created by ComPiere are Copyright (C) ComPiere, Inc.;   All Rights Reserved.
  * Contributor(s): Openbravo SLU
- * Contributions are Copyright (C) 2001-2013 Openbravo S.L.U.
+ * Contributions are Copyright (C) 2001-2019 Openbravo S.L.U.
  ******************************************************************************/
 package org.openbravo.erpCommon.ad_forms;
 
 import java.sql.Connection;
-import java.sql.Statement;
+import java.sql.PreparedStatement;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.List;
 
+import org.apache.commons.lang.StringUtils;
 import org.apache.logging.log4j.LogManager;
 import org.apache.logging.log4j.Logger;
 import org.openbravo.database.ConnectionProvider;
@@ -38,6 +42,7 @@
   public TranslationHandler(ConnectionProvider cDB) {
     m_AD_Client_ID = 0;
     DB = cDB;
+    parameters = new ArrayList<>();
   }
 
   public TranslationHandler(int AD_Client_ID, ConnectionProvider cDB, Connection con) {
@@ -45,6 +50,7 @@
     m_AD_Client_ID = AD_Client_ID;
     DB = cDB;
     this.con = con;
+    parameters = new ArrayList<>();
 
   } // TranslationHandler
 
@@ -65,16 +71,18 @@
   /** Current ColumnName */
   private String m_curColumnName = null;
   /** Current Value */
-  private StringBuffer m_curValue = null;
+  private String m_curValue = null;
   /** Original Value */
   private String m_oriValue = null;
   /** SQL */
-  private StringBuffer m_sql = null;
+  private String m_sql = null;
 
   private int m_updateCount = 0;
 
   private String m_Translated = null;
 
+  private List<String> parameters;
+
   static Logger log4j = LogManager.getLogger();
 
   /*************************************************************************/
@@ -99,17 +107,17 @@
       m_AD_Language = attributes.getValue(TranslationManager.XML_ATTRIBUTE_LANGUAGE);
 
       m_TableName = attributes.getValue(TranslationManager.XML_ATTRIBUTE_TABLE);
-      m_updateSQL = "UPDATE " + m_TableName;
+      m_updateSQL = "update " + m_TableName;
 
       m_updateSQL += "_Trl";
-      m_updateSQL += " SET ";
+      m_updateSQL += " set ";
       if (log4j.isDebugEnabled()) {
         log4j.debug("AD_Language=" + m_AD_Language + ", TableName=" + m_TableName);
       }
     } else if (qName.equals(TranslationManager.XML_ROW_TAG)) {
       m_curID = attributes.getValue(TranslationManager.XML_ROW_ATTRIBUTE_ID);
       m_Translated = attributes.getValue(TranslationManager.XML_ROW_ATTRIBUTE_TRANSLATED);
-      m_sql = new StringBuffer();
+      m_sql = "";
     } else if (qName.equals(TranslationManager.XML_VALUE_TAG)) {
       m_curColumnName = attributes.getValue(TranslationManager.XML_VALUE_ATTRIBUTE_COLUMN);
       m_oriValue = attributes.getValue(TranslationManager.XML_VALUE_ATTRIBUTE_ORIGINAL);
@@ -118,7 +126,7 @@
     } else {
       log4j.error("startElement - UNKNOWN TAG: " + qName);
     }
-    m_curValue = new StringBuffer();
+    m_curValue = "";
   } // startElement
 
   /**
@@ -133,8 +141,8 @@
    * @throws SAXException
    */
   @Override
-  public void characters(char ch[], int start, int length) throws SAXException {
-    m_curValue.append(ch, start, length);
+  public void characters(char[] ch, int start, int length) throws SAXException {
+    m_curValue += new String(ch, start, length);
   } // characters
 
   /**
@@ -158,67 +166,81 @@
     } else if (qName.equals(TranslationManager.XML_ROW_TAG)) {
       // Set section
       if (m_sql.length() > 0) {
-        m_sql.append(",");
+        m_sql += ",";
       }
-      m_sql.append("Updated=now()"); // .append(DB.TO_DATE(m_time,
-      // false));
-      m_sql.append(",IsTranslated='" + m_Translated + "'");
+      m_sql += "Updated=now() ,IsTranslated=?";
+      parameters.add(m_Translated);
       // Where section
-      m_sql.append(" WHERE ").append(m_TableName).append("_ID='").append(m_curID).append("'");
-      m_sql.append(" AND AD_Language='").append(m_AD_Language).append("'");
+      //@formatter:off
+      m_sql += 
+              " where " + m_TableName + "_ID=?" + 
+              "   and AD_Language=?";
+      //@formatter:on
+      parameters.add(m_curID);
+      parameters.add(m_AD_Language);
       if (m_AD_Client_ID >= 0) {
-        m_sql.append(" AND AD_Client_ID='").append(m_AD_Client_ID).append("'");
+        m_sql += "  and AD_Client_ID=?";
+        parameters.add(Integer.toString(m_AD_Client_ID));
       }
       // Update section
-      m_sql.insert(0, m_updateSQL);
+      m_sql = m_updateSQL + m_sql;
       if (log4j.isDebugEnabled()) {
-        log4j.debug(m_sql.toString());
+        log4j.debug(m_sql);
       }
       // Execute
       int no = 0;
       //
-      Statement st = null;
+      PreparedStatement st = null;
       try {
-        st = DB.getStatement(con);
-        no = st.executeUpdate(m_sql.toString());
+        st = DB.getPreparedStatement(con, m_sql);
+        int paramCount = 1;
+        for (String parameter : parameters) {
+          st.setString(paramCount, parameter);
+          paramCount++;
+        }
+
+        no = st.executeUpdate();
       } catch (Exception e) {
-        log4j.error("183:" + m_sql.toString() + e.toString());
+        log4j.error("183:" + m_sql + e.toString());
       } finally {
         try {
-          DB.releaseTransactionalStatement(st);
-        } catch (Exception ignored) {
+          DB.releaseTransactionalPreparedStatement(st);
+        } catch (SQLException e) {
+          // This exception is ignored.
         }
+        parameters.clear();
       }
 
       if (no == 1) {
         if (log4j.isDebugEnabled()) {
-          log4j.debug(m_sql.toString());
+          log4j.debug(m_sql);
         }
         m_updateCount++;
       } else if (no == 0) {
-        log4j.info("Not Found - " + m_sql.toString());
+        log4j.info("Not Found - " + m_sql);
       } else {
-        log4j.error("Update Rows=" + no + " (Should be 1) - " + m_sql.toString());
+        log4j.error("Update Rows=" + no + " (Should be 1) - " + m_sql);
       }
     } else if (qName.equals(TranslationManager.XML_VALUE_TAG)) {
       String value = "";
-      if (m_curValue != null && !m_curValue.toString().equals("")) {
-        value = TO_STRING(m_curValue.toString());
-      } else if (m_oriValue != null && !m_oriValue.toString().equals("")) {
-        value = TO_STRING(m_oriValue.toString());
+      if (StringUtils.isNotEmpty(m_curValue)) {
+        value = TO_STRING(m_curValue);
+      } else if (StringUtils.isNotEmpty(m_oriValue)) {
+        value = TO_STRING(m_oriValue);
       }
-      if (!value.equals("")) {
+      if (StringUtils.isNotEmpty(value)) {
         if (m_sql.length() > 0) {
-          m_sql.append(",");
+          m_sql += ", ";
         }
-        m_sql.append(m_curColumnName).append("=").append(value);
+        m_sql += m_curColumnName + "=?";
+        parameters.add(value);
       }
     } else if (qName.equals(TranslationManager.XML_CONTRIB)) {
       if (log4j.isDebugEnabled()) {
-        log4j.debug("Contibutors:" + TO_STRING(m_curValue.toString()));
+        log4j.debug("Contibutors:" + TO_STRING(m_curValue));
       }
       try {
-        TranslationData.insertContrib(DB, m_curValue.toString(), m_AD_Language);
+        TranslationData.insertContrib(DB, m_curValue, m_AD_Language);
       } catch (Exception e) {
         log4j.error(e.toString());
       }
@@ -241,20 +263,18 @@
   /**
    * Package Strings for SQL command.
    * 
-   * <pre>
-   * 	-	include in ' (single quotes)
-   * 	-	replace ' with ''
-   * </pre>
+   * Because we are using prepared statements we don't have to escape single quotes, so this method
+   * only gets a substring of maxLength from the string provided
    * 
    * @param txt
    *          String with text
    * @param maxLength
    *          Maximum Length of content or 0 to ignore
-   * @return escaped string for insert statement (NULL if null or empty)
+   * @return escaped string for insert statement (null if null or empty)
    */
   private String TO_STRING(String txt, int maxLength) {
     if (txt == null || txt.isEmpty()) {
-      return "NULL";
+      return null;
     }
 
     // Length
@@ -263,21 +283,7 @@
       text = txt.substring(0, maxLength);
     }
 
-    char quote = '\'';
-    // copy characters (wee need to look through anyway)
-    StringBuffer out = new StringBuffer();
-    out.append(quote); // '
-    for (int i = 0; i < text.length(); i++) {
-      char c = text.charAt(i);
-      if (c == quote) {
-        out.append("''");
-      } else {
-        out.append(c);
-      }
-    }
-    out.append(quote); // '
-    //
-    return out.toString();
+    return text;
   } // TO_STRING
 
 } // TranslationHandler
--- a/src/org/openbravo/erpCommon/ad_forms/TranslationManager.java	Wed Nov 20 17:29:27 2019 +0100
+++ b/src/org/openbravo/erpCommon/ad_forms/TranslationManager.java	Tue Oct 08 11:48:18 2019 +0200
@@ -20,9 +20,11 @@
 import java.io.FileWriter;
 import java.io.OutputStreamWriter;
 import java.sql.Connection;
+import java.sql.PreparedStatement;
 import java.sql.ResultSet;
 import java.sql.SQLException;
-import java.sql.Statement;
+import java.util.ArrayList;
+import java.util.List;
 
 import javax.xml.parsers.ParserConfigurationException;
 import javax.xml.parsers.SAXParser;
@@ -401,8 +403,9 @@
       String rootDirectory, String moduleId, String moduleLanguage, String javaPackage,
       boolean trl) {
 
-    Statement st = null;
-    StringBuffer sql = null;
+    PreparedStatement st = null;
+    String sql = null;
+    List<String> parameters = new ArrayList<>();
     try {
       String trlTable = table;
       if (trl && !table.endsWith("_TRL")) {
@@ -424,41 +427,36 @@
       }
 
       // Prepare query to retrieve translated rows
-      sql = new StringBuffer("SELECT ");
+      sql = "select ";
       if (trl) {
-        sql.append("t.IsTranslated,");
+        sql += "t.IsTranslated,";
       } else {
-        sql.append("'N', ");
+        sql += "'N', ";
       }
-      sql.append("t.").append(keyColumn);
+      sql += "t." + keyColumn;
 
       for (int i = 0; i < trlColumns.length; i++) {
-        sql.append(", t.")
-            .append(trlColumns[i].c)
-            .append(",o.")
-            .append(trlColumns[i].c)
-            .append(" AS ")
-            .append(trlColumns[i].c)
-            .append("O");
+        sql += ", t." + trlColumns[i].c + ", o." + trlColumns[i].c + " AS " + trlColumns[i].c + "O";
       }
 
-      sql.append(" FROM ").append(trlTable).append(" t").append(", ").append(table).append(" o");
+      sql += " from " + trlTable + " t, " + table + " o";
 
       if (exportReferenceData && !exportAll) {
-        sql.append(", AD_REF_DATA_LOADED DL");
+        sql += ", AD_REF_DATA_LOADED DL";
       }
 
-      sql.append(" WHERE ");
+      sql += " where ";
       if (trl) {
-        sql.append("t.AD_Language='" + AD_Language + "'").append(" AND ");
+        sql += "t.AD_Language=? AND ";
+        parameters.add(AD_Language);
       }
-      sql.append("o.").append(keyColumn).append("= t.").append(keyColumn);
+      sql += "o." + keyColumn + "= t." + keyColumn;
 
       if (m_IsCentrallyMaintained) {
-        sql.append(" AND ").append("o.IsCentrallyMaintained='N'");
+        sql += " and o.IsCentrallyMaintained='N'";
       }
       // AdClient !=0 not supported
-      sql.append(" AND o.AD_Client_ID='0' ");
+      sql += " and o.AD_Client_ID='0' ";
 
       if (!exportReferenceData) {
         String tempTrlTableName = trlTable;
@@ -468,60 +466,64 @@
         final TranslationData[] parentTable = TranslationData.parentTable(cp, tempTrlTableName);
 
         if (parentTable.length == 0) {
-          sql.append(" AND ").append(" o.ad_module_id='").append(moduleId).append("'");
+          sql += " and o.ad_module_id=?";
+          parameters.add(moduleId);
         } else {
           /** Search for ad_module_id in the parent table */
           if (StringUtils.isEmpty(parentTable[0].grandparent)) {
             String strParentTable = parentTable[0].tablename;
-            sql.append(" AND ");
-            sql.append(" exists ( select 1 from ").append(strParentTable).append(" p ");
-            sql.append("   where p.")
-                .append(strParentTable + "_ID")
-                .append("=")
-                .append("o." + strParentTable + "_ID");
-            sql.append("   and p.ad_module_id='").append(moduleId).append("')");
+            //@formatter:off
+            sql += "  and exists ( " +
+                   "   select 1 " +
+                   "     from " + strParentTable + " p " + 
+                   "    where p." + strParentTable + "_ID = o." + strParentTable + "_ID " +
+                   "      and p.ad_module_id=?)";
+            //@formatter:on
+            parameters.add(moduleId);
           } else {
             String strParentTable = parentTable[0].tablename;
             String strGandParentTable = parentTable[0].grandparent;
 
-            sql.append(" AND ");
-            sql.append(" exists ( select 1 from ")
-                .append(strGandParentTable)
-                .append(" gp, ")
-                .append(strParentTable)
-                .append(" p");
-            sql.append("   where p.")
-                .append(strParentTable + "_ID")
-                .append("=")
-                .append("o." + strParentTable + "_ID");
-            sql.append("   and p." + strGandParentTable + "_ID = gp." + strGandParentTable + "_ID");
-            sql.append("   and gp.ad_module_id='").append(moduleId).append("')");
+            //@formatter:off
+            sql += "  and exists (" +
+                   "   select 1 " +
+                   "     from " + strGandParentTable + " gp, " + strParentTable + " p " +
+                   "    where p." + strParentTable + "_ID = o." + strParentTable + "_ID " +
+                   "      and p." + strGandParentTable + "_ID = gp." + strGandParentTable + "_ID " +
+                   "      and gp.ad_module_id = ?)";
+            //@formatter:on
+            parameters.add(moduleId);
           }
         }
       }
       if (exportReferenceData && !exportAll) {
-        sql.append(" AND DL.GENERIC_ID = o.")
-            .append(keyColumn)
-            .append(" AND DL.AD_TABLE_ID = '")
-            .append(tableID)
-            .append("'")
-            .append(" AND DL.AD_MODULE_ID = '")
-            .append(moduleId)
-            .append("'");
+        //@formatter:off
+        sql += 
+               " and DL.GENERIC_ID = o." + keyColumn + 
+               " and DL.AD_TABLE_ID = ?" +
+               " and DL.AD_MODULE_ID = ?";
+        //@formatter:on
+        parameters.add(tableID);
+        parameters.add(moduleId);
       }
 
-      sql.append(" ORDER BY t.").append(keyColumn);
+      sql += " order by t." + keyColumn;
       //
 
       if (log4j.isDebugEnabled()) {
-        log4j.debug("SQL:" + sql.toString());
+        log4j.debug("SQL:" + sql);
       }
-      st = cp.getStatement();
+      st = cp.getPreparedStatement(sql);
       if (log4j.isDebugEnabled()) {
         log4j.debug("st");
       }
+      int paramCounter = 1;
+      for (String parameter : parameters) {
+        st.setString(paramCounter, parameter);
+        paramCounter++;
+      }
 
-      final ResultSet rs = st.executeQuery(sql.toString());
+      final ResultSet rs = st.executeQuery();
       if (log4j.isDebugEnabled()) {
         log4j.debug("rs");
       }
--- a/src/org/openbravo/erpCommon/ad_process/HeartbeatProcess.java	Wed Nov 20 17:29:27 2019 +0100
+++ b/src/org/openbravo/erpCommon/ad_process/HeartbeatProcess.java	Tue Oct 08 11:48:18 2019 +0200
@@ -11,7 +11,7 @@
  * under the License. 
  * The Original Code is Openbravo ERP. 
  * The Initial Developer of the Original Code is Openbravo SLU 
- * All portions are Copyright (C) 2008-2018 Openbravo SLU 
+ * All portions are Copyright (C) 2008-2019 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -221,7 +221,6 @@
   private String createQueryStr(String beatType) {
     logger.logln(logger.messageDb("HB_QUERY", ctx.getLanguage()));
 
-    StringBuilder sb = new StringBuilder();
     if (!(DECLINING_BEAT.equals(beatType) || DEFERRING_BEAT.equals(beatType))) {
       // Complete beat with all available instance info
       try {
@@ -238,18 +237,24 @@
     }
 
     Enumeration<?> e = props.propertyNames();
+    String sb = "";
     while (e.hasMoreElements()) {
       String elem = (String) e.nextElement();
       String value = props.getProperty(elem);
       try {
-        sb.append(elem + "=" + (value == null ? "" : URLEncoder.encode(value, "UTF-8")) + "&");
+        if (value != null) {
+          value = URLEncoder.encode(value, "UTF-8");
+        } else {
+          value = "";
+        }
+        sb += elem + "=" + value + "&";
       } catch (UnsupportedEncodingException e1) {
         log.error("Error encoding", e1);
       }
     }
-    sb.append("beatType=" + beatType);
+    sb += "beatType=" + beatType;
 
-    return sb.toString();
+    return sb;
   }
 
   /**
--- a/src/org/openbravo/erpCommon/businessUtility/Preferences.java	Wed Nov 20 17:29:27 2019 +0100
+++ b/src/org/openbravo/erpCommon/businessUtility/Preferences.java	Tue Oct 08 11:48:18 2019 +0200
@@ -376,59 +376,61 @@
       boolean checkWindow, Map<QueryFilter, Boolean> queryFilters) {
 
     Map<String, Object> parameters = new HashMap<>();
-    StringBuilder hql = new StringBuilder();
-    hql.append(" as p ");
-    hql.append(" where ");
+    //@formatter:off
+    String hql = 
+            " as p " + 
+            " where ";
+    //@formatter:on
     if (exactMatch) {
       if (client != null) {
-        hql.append(" p.visibleAtClient.id = :clientId ");
+        hql += " p.visibleAtClient.id = :clientId ";
         parameters.put("clientId", client);
       } else {
-        hql.append(" p.visibleAtClient is null");
+        hql += " p.visibleAtClient is null ";
       }
       if (org != null) {
-        hql.append(" and p.visibleAtOrganization.id = :orgId ");
+        hql += " and p.visibleAtOrganization.id = :orgId ";
         parameters.put("orgId", org);
       } else {
-        hql.append(" and p.visibleAtOrganization is null ");
+        hql += " and p.visibleAtOrganization is null ";
       }
 
       if (user != null) {
-        hql.append(" and p.userContact.id = :userId ");
+        hql += " and p.userContact.id = :userId ";
         parameters.put("userId", user);
       } else {
-        hql.append(" and p.userContact is null ");
+        hql += " and p.userContact is null ";
       }
 
       if (role != null) {
-        hql.append(" and p.visibleAtRole.id = :roleId ");
+        hql += " and p.visibleAtRole.id = :roleId";
         parameters.put("roleId", role);
       } else {
-        hql.append(" and p.visibleAtRole is null");
+        hql += " and p.visibleAtRole is null ";
       }
 
       if (window != null) {
-        hql.append(" and p.window.id = :windowId ");
+        hql += " and p.window.id = :windowId ";
         parameters.put("windowId", window);
       } else {
-        hql.append(" and p.window is null");
+        hql += " and p.window is null ";
       }
     } else {
       if (client != null) {
-        hql.append(" (p.visibleAtClient.id = :clientId or ");
+        hql += " (p.visibleAtClient.id = :clientId or ";
         parameters.put("clientId", client);
       } else {
-        hql.append(" (");
+        hql += " (";
       }
-      hql.append(" coalesce(p.visibleAtClient, '0')='0') ");
+      hql += " coalesce(p.visibleAtClient, '0')='0') ";
 
       if (role != null) {
-        hql.append(" and   (p.visibleAtRole.id = :roleId or ");
+        hql += " and (p.visibleAtRole.id = :roleId or ";
         parameters.put("roleId", role);
       } else {
-        hql.append(" and (");
+        hql += " and (";
       }
-      hql.append("        p.visibleAtRole is null) ");
+      hql += " p.visibleAtRole is null) ";
 
       List<String> parentOrgs;
       if (org == null) {
@@ -439,41 +441,41 @@
             .getParentList(org, true);
       }
 
-      hql.append("     and coalesce(p.visibleAtOrganization.id, '0') in :parentOrgs");
+      hql += " and coalesce(p.visibleAtOrganization.id, '0') in :parentOrgs";
       parameters.put("parentOrgs", parentOrgs);
 
       if (user != null) {
-        hql.append("  and (p.userContact.id = :userId or ");
+        hql += " and (p.userContact.id = :userId or ";
         parameters.put("userId", user);
       } else {
-        hql.append(" and (");
+        hql += " and (";
       }
-      hql.append("         p.userContact is null) ");
+      hql += " p.userContact is null) ";
       if (checkWindow) {
         if (window != null) {
-          hql.append(" and  (p.window.id = :windowId or ");
+          hql += " and (p.window.id = :windowId or ";
           parameters.put("windowId", window);
         } else {
-          hql.append(" and (");
+          hql += " and (";
         }
-        hql.append("        p.window is null) ");
+        hql += " p.window is null) ";
       }
     }
 
     if (property != null) {
-      hql.append(" and p.propertyList = :isListProperty");
+      hql += " and p.propertyList = :isListProperty";
       parameters.put("isListProperty", isListProperty);
       if (isListProperty) {
-        hql.append(" and p.property = :property ");
+        hql += " and p.property = :property ";
       } else {
-        hql.append(" and p.attribute = :property ");
+        hql += " and p.attribute = :property";
       }
       parameters.put("property", property);
     }
 
-    hql.append(" order by p.id");
+    hql += " order by p.id";
 
-    OBQuery<Preference> qPref = OBDal.getInstance().createQuery(Preference.class, hql.toString());
+    OBQuery<Preference> qPref = OBDal.getInstance().createQuery(Preference.class, hql);
     qPref.setNamedParameters(parameters);
     if (queryFilters != null && queryFilters.size() > 0) {
       qPref.setFilterOnActive(queryFilters.get(QueryFilter.ACTIVE));
--- a/src/org/openbravo/erpCommon/obps/ActivationKey.java	Wed Nov 20 17:29:27 2019 +0100
+++ b/src/org/openbravo/erpCommon/obps/ActivationKey.java	Tue Oct 08 11:48:18 2019 +0200
@@ -1714,21 +1714,22 @@
   }
 
   private void initializeWsCounter() {
-    StringBuilder hql = new StringBuilder();
-    hql.append("select min(creationDate)\n");
-    hql.append("  from ADSession\n");
-    hql.append(" where loginStatus = 'WS'\n");
-    hql.append("   and creationDate > :firstDay\n");
-    hql.append(" group by day(creationDate), month(creationDate), year(creationDate)\n");
-    hql.append("having count(*) > :maxWsPerDay\n");
-    hql.append(" order by 1\n");
-
+    //@formatter:off
+    String hql = 
+            "select min(creationDate) " +
+            "  from ADSession " +
+            " where loginStatus = 'WS' " +
+            "   and creationDate > :firstDay " +
+            " group by day(creationDate), month(creationDate), year(creationDate) " +
+            "   having count(*) > :maxWsPerDay " +
+            " order by 1";
+    //@formatter:on
     Query<Date> qExceededDays = OBDal.getInstance()
         .getSession()
-        .createQuery(hql.toString(), Date.class);
-    qExceededDays.setParameter("firstDay",
-        new Date(getDayAt0(new Date()).getTime() - WS_MS_EXCEEDING_ALLOWED_PERIOD));
-    qExceededDays.setParameter("maxWsPerDay", maxWsCalls);
+        .createQuery(hql, Date.class)
+        .setParameter("firstDay",
+            new Date(getDayAt0(new Date()).getTime() - WS_MS_EXCEEDING_ALLOWED_PERIOD))
+        .setParameter("maxWsPerDay", maxWsCalls);
 
     exceededInLastDays = new ArrayList<Date>();
 
--- a/src/org/openbravo/erpCommon/utility/SystemInfo.java	Wed Nov 20 17:29:27 2019 +0100
+++ b/src/org/openbravo/erpCommon/utility/SystemInfo.java	Tue Oct 08 11:48:18 2019 +0200
@@ -11,7 +11,7 @@
  * under the License. 
  * The Original Code is Openbravo ERP. 
  * The Initial Developer of the Original Code is Openbravo SLU 
- * All portions are Copyright (C) 2008-2018 Openbravo SLU 
+ * All portions are Copyright (C) 2008-2019 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -647,14 +647,14 @@
    */
   private static void loadSessionInfo() {
     // Obtain login counts
-    StringBuilder hql = new StringBuilder();
-    hql.append("select min(s.creationDate) as firstLogin, ");
-    hql.append("       max(s.creationDate) as lastLogin, ");
-    hql.append("       count(*) as totalLogins");
-    hql.append("  from ADSession s");
-    Query<Object[]> q = OBDal.getInstance()
-        .getSession()
-        .createQuery(hql.toString(), Object[].class);
+    //@formatter:off
+    String hql = 
+            "select min(s.creationDate) as firstLogin, " +
+            "       max(s.creationDate) as lastLogin, " +
+            "       count(*) as totalLogins " +
+            "  from ADSession s";
+    //@formatter:on
+    Query<Object[]> q = OBDal.getInstance().getSession().createQuery(hql, Object[].class);
     if (q.list().size() != 0) {
       Object[] logInfo = q.list().get(0);
       firstLogin = (Date) logInfo[0];
@@ -786,15 +786,19 @@
   }
 
   private static List<Long> getWsLogins(String type, Date fromDate) {
-    StringBuilder hql = new StringBuilder();
-    hql.append("select count(*)\n");
-    hql.append("  from ADSession\n");
-    hql.append(" where loginStatus = :type\n");
-    hql.append("   and creationDate > :firstDay\n");
-    hql.append(" group by day(creationDate), month(creationDate), year(creationDate)\n");
-    Query<Long> qWs = OBDal.getInstance().getSession().createQuery(hql.toString(), Long.class);
-    qWs.setParameter("firstDay", fromDate);
-    qWs.setParameter("type", type);
+    //@formatter:off
+    String hql = 
+            "select count(*) " +
+            "  from ADSession " +
+            " where loginStatus = :type " +
+            "   and creationDate > :firstDay " +
+            " group by day(creationDate), month(creationDate), year(creationDate) ";
+    //@formatter:on
+    Query<Long> qWs = OBDal.getInstance()
+        .getSession()
+        .createQuery(hql, Long.class)
+        .setParameter("firstDay", fromDate)
+        .setParameter("type", type);
     return qWs.list();
   }
 
--- a/src/org/openbravo/erpCommon/utility/Utility.java	Wed Nov 20 17:29:27 2019 +0100
+++ b/src/org/openbravo/erpCommon/utility/Utility.java	Tue Oct 08 11:48:18 2019 +0200
@@ -2629,23 +2629,25 @@
    * @param fieldId
    *          ID of the field to look for.
    * @param language
-   *          Langage to get the name in.
+   *          Language to get the name in.
    * @return field name in the correct language.
    */
   public static String getFieldName(String fieldId, String language) {
-    StringBuilder hql = new StringBuilder();
-    hql.append("select (select t.name\n");
-    hql.append("          from ADFieldTrl t\n");
-    hql.append("         where t.field = f\n");
-    hql.append("           and t.language.language=:lang),\n");
-    hql.append("       f.name\n");
-    hql.append("  from ADField f\n");
-    hql.append(" where f.id =:fieldId\n");
+    //@formatter:off
+    String hql = 
+            "select (" +
+            "    select t.name " +
+            "      from ADFieldTrl t " +
+            "     where t.field = f " +
+            "       and t.language.language=:lang), f.name " +
+            "  from ADField f " +
+            " where f.id = :fieldId ";
+    //@formatter:on
     Query<Object[]> qName = OBDal.getInstance()
         .getSession()
-        .createQuery(hql.toString(), Object[].class);
-    qName.setParameter("lang", language);
-    qName.setParameter("fieldId", fieldId);
+        .createQuery(hql, Object[].class)
+        .setParameter("lang", language)
+        .setParameter("fieldId", fieldId);
 
     if (qName.list().isEmpty()) {
       log4j.warn("Not found name for fieldId " + fieldId);
--- a/src/org/openbravo/service/dataset/DataSetService.java	Wed Nov 20 17:29:27 2019 +0100
+++ b/src/org/openbravo/service/dataset/DataSetService.java	Tue Oct 08 11:48:18 2019 +0200
@@ -11,7 +11,7 @@
  * under the License. 
  * The Original Code is Openbravo ERP. 
  * The Initial Developer of the Original Code is Openbravo SLU 
- * All portions are Copyright (C) 2008-2018 Openbravo SLU 
+ * All portions are Copyright (C) 2008-2019 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -20,6 +20,7 @@
 package org.openbravo.service.dataset;
 
 import java.math.BigInteger;
+import java.security.InvalidParameterException;
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.Comparator;
@@ -29,6 +30,7 @@
 import java.util.List;
 import java.util.Map;
 
+import org.apache.commons.lang.StringUtils;
 import org.apache.logging.log4j.LogManager;
 import org.apache.logging.log4j.Logger;
 import org.hibernate.criterion.Restrictions;
@@ -260,32 +262,15 @@
       }
 
       String whereClause = dataSetTable.getSQLWhereClause();
+      final Map<String, Object> paramsInWhereClause = new HashMap<>();
 
-      final Map<String, Object> existingParams = new HashMap<String, Object>();
-      if (whereClause != null) {
-        if (parameters != null) {
-          for (final String name : parameters.keySet()) {
-            if (whereClause.indexOf(":" + name) != -1) {
-              final Object value = parameters.get(name);
-              existingParams.put(name, "null".equals(value) ? null : value);
-            }
-          }
-        }
-      }
-
-      if (moduleId != null && whereClause != null) {
-        while (whereClause.indexOf("@moduleid@") != -1) {
-          whereClause = whereClause.replace("@moduleid@", "'" + moduleId + "'");
-        }
-        if (whereClause.indexOf(":moduleid") != -1 && parameters.get("moduleid") == null) {
-          existingParams.put("moduleid", moduleId);
-        }
-      }
+      whereClause = getWhereClauseWithAliasesReplaced(moduleId, parameters, whereClause,
+          paramsInWhereClause);
 
       final OBQuery<BaseOBObject> oq = OBDal.getInstance()
-          .createQuery(entity.getName(), whereClause);
-      oq.setFilterOnActive(false);
-      oq.setNamedParameters(existingParams);
+          .createQuery(entity.getName(), whereClause)
+          .setFilterOnActive(false)
+          .setNamedParameters(paramsInWhereClause);
 
       if (OBContext.getOBContext().getRole().getId().equals("0")
           && OBContext.getOBContext().getCurrentClient().getId().equals("0")) {
@@ -302,6 +287,46 @@
   }
 
   /**
+   * Gets the whereClause and its corresponding parameters
+   * 
+   * @param moduleId
+   *          ModuleId to put in parameters
+   * @param parameters
+   *          Parameter map
+   * @param whereClauseWithAliases
+   *          Original where clause with parameters not set
+   * @param paramsInWhereClause
+   *          New map with found parameters in this where clause
+   * @return whereClause ready for execution and existingParams set
+   */
+  private String getWhereClauseWithAliasesReplaced(String moduleId, Map<String, Object> parameters,
+      String whereClauseWithAliases, Map<String, Object> paramsInWhereClause) {
+    String whereClause = whereClauseWithAliases;
+    if (whereClauseWithAliases != null) {
+      if (parameters != null) {
+        String finalWhereClause = whereClause;
+        parameters.keySet()
+            .stream()
+            .filter(name -> finalWhereClause.contains(":" + name))
+            .forEach(name -> paramsInWhereClause.put(name,
+                "null".equals(parameters.get(name)) ? null : parameters.get(name)));
+      }
+      if (moduleId != null) {
+        // Minimal checking that the moduleId has no spaces and seems to be an alphanumeric string
+        if (StringUtils.isAlphanumeric(moduleId)) {
+          if (whereClauseWithAliases.contains(":moduleid")) {
+            paramsInWhereClause.putIfAbsent("moduleid", moduleId);
+          }
+          whereClause = whereClauseWithAliases.replaceAll("@moduleid@", "'" + moduleId + "'");
+        } else {
+          throw new InvalidParameterException("ModuleId not valid");
+        }
+      }
+    }
+    return whereClause;
+  }
+
+  /**
    * Determines which objects are exportable using the DataSetTable whereClause. Returns an iterator
    * over these objects. The returned objects are sorted by id.
    * 
@@ -321,25 +346,13 @@
 
     if (entity == null) {
       log.error("Entity not found using table name " + entityName);
-      return new ArrayList<BaseOBObject>().iterator();
+      return Collections.emptyIterator();
     }
 
     String whereClause = dataSetTable.getSQLWhereClause();
-    final Map<String, Object> existingParams = new HashMap<String, Object>();
-    for (final String name : parameters.keySet()) {
-      if (whereClause.indexOf(":" + name) != -1) {
-        final Object value = parameters.get(name);
-        existingParams.put(name, "null".equals(value) ? null : value);
-      }
-    }
-    if (moduleId != null && whereClause != null) {
-      while (whereClause.indexOf("@moduleid@") != -1) {
-        whereClause = whereClause.replace("@moduleid@", "'" + moduleId + "'");
-      }
-      if (whereClause.indexOf(":moduleid") != -1 && parameters.get("moduleid") == null) {
-        existingParams.put("moduleid", moduleId);
-      }
-    }
+    final Map<String, Object> paramsInWhereClause = new HashMap<>();
+    whereClause = getWhereClauseWithAliasesReplaced(moduleId, parameters, whereClause,
+        paramsInWhereClause);
 
     // set the order by, first detect if there is an alias
     String alias = "";
@@ -352,12 +365,15 @@
       alias = strippedWhereClause.substring(0, index);
       alias += ".";
     }
-
+    String hql = "";
+    if (whereClause != null) {
+      hql += whereClause;
+    }
+    hql += " order by " + alias + "id";
     final OBQuery<BaseOBObject> oq = OBDal.getInstance()
-        .createQuery(entity.getName(),
-            (whereClause != null ? whereClause : "") + " order by " + alias + "id");
-    oq.setFilterOnActive(false);
-    oq.setNamedParameters(existingParams);
+        .createQuery(entity.getName(), hql)
+        .setFilterOnActive(false)
+        .setNamedParameters(paramsInWhereClause);
 
     if (OBContext.getOBContext().getRole().getId().equals("0")
         && OBContext.getOBContext().getCurrentClient().getId().equals("0")) {
--- a/src/org/openbravo/service/rest/DalWebService.java	Wed Nov 20 17:29:27 2019 +0100
+++ b/src/org/openbravo/service/rest/DalWebService.java	Tue Oct 08 11:48:18 2019 +0200
@@ -80,7 +80,6 @@
   // Parameter to specify the list of properties to be returned
   public static final String PARAMETER_PROPERTIES = "_selectedProperties";
   public static final String PARAMETER_NO_ACTIVE_FILTER = "_noActiveFilter";
-  private static final String ID = "id";
 
   /**
    * Performs the GET REST operation. This service handles multiple types of request: the request
@@ -233,10 +232,10 @@
         }
       } else {
         final OBQuery<BaseOBObject> obq = OBDal.getInstance()
-            .createQuery(entityName, ID + " = :bobId");
-        obq.setNamedParameter("bobId", id);
-        obq.setFilterOnActive(false);
-        obq.setMaxResult(1);
+            .createQuery(entityName, " id = :bobId")
+            .setNamedParameter("bobId", id)
+            .setFilterOnActive(false)
+            .setMaxResult(1);
         final BaseOBObject result = obq.uniqueResult();
 
         if (result == null) {