fixes issue 37064: upgrade hibernate to version 5.3.2
authorCarlos Aristu <carlos.aristu@openbravo.com>
Tue, 24 Jul 2018 10:44:21 +0200
changeset 34458 95dcfa93d706
parent 34309 e2c56d84d26d (current diff)
parent 34457 309779aad0d3 (diff)
child 34459 328be6af97c0
fixes issue 37064: upgrade hibernate to version 5.3.2
lib/runtime/hibernate-jpa-2.0-api-1.0.0.Final.jar
lib/runtime/hibernate3-patched.jar
lib/runtime/javassist-3.20.0-GA.jar
lib/runtime/jta.jar
src/org/openbravo/dal/core/OBDynamicPropertyHandler.java
src/org/openbravo/dal/core/OBDynamicTuplizer.java
src/org/openbravo/dal/core/OBTuplizer.java
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/legal/ASM_BSD_license.txt	Tue Jul 24 10:44:21 2018 +0200
@@ -0,0 +1,29 @@
+ASM is released under the following 3-Clause BSD License:
+
+ASM: a very small and fast Java bytecode manipulation framework
+Copyright (c) 2000-2011 INRIA, France Telecom
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions
+are met:
+1. Redistributions of source code must retain the above copyright
+  notice, this list of conditions and the following disclaimer.
+2. Redistributions in binary form must reproduce the above copyright
+  notice, this list of conditions and the following disclaimer in the
+  documentation and/or other materials provided with the distribution.
+3. Neither the name of the copyright holders nor the names of its
+  contributors may be used to endorse or promote products derived from
+  this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+THE POSSIBILITY OF SUCH DAMAGE.
--- a/legal/Licensing.txt	Tue Jul 24 10:39:37 2018 +0200
+++ b/legal/Licensing.txt	Tue Jul 24 10:44:21 2018 +0200
@@ -67,7 +67,13 @@
 # Eclipse icons 
 # wsdl4j-1.5.1.jar
 Icons and files under the Eclipse Public License (license available at
-http://www.eclipse.org/legal/epl-v10.html
+http://www.eclipse.org/legal/epl-v10.html)
+
+# javax.persistence-api-2.2.jar
+Under the terms of the Eclipse Public License v 1.0 (license available at
+http://www.eclipse.org/legal/epl-v10.html) 
+and Eclipse Distribution License v 1.0 (license available at 
+http://www.eclipse.org/org/documents/edl-v10.php)
 
 # nekohtml.jar (CyberNeko HTML Parser)
 Under the CyberNeko Software License, Version 1.0 (license available at
@@ -165,7 +171,8 @@
 # poi-3.10.1.jar
 Under the Apache 2.0 license (included as Apache_poi_license.txt in this folder)
 
-# hibernate3-patched.jar
+# hibernate-core-5.3.2.Final.jar
+# hibernate-commons-annotations-5.0.4.Final.jar
 All files under the LGPL 2.1 (available at www.gnu.org/licenses/lgpl.html)
 
 # dom4j-1.6.1.jar
@@ -185,7 +192,7 @@
 Under MPL/GPL License (available at https://developer.mozilla.org/en/Rhino_License)
 ob-rhino-1.6R7.jar is the same code as js.jar repackaged to be available under org.openbravo
 
-# javassist-3.20.0-GA.jar
+# javassist-3.22.0-GA.jar
 Under MPL License (included as MPL-1.1.txt in this folder)
 
 # slf4j-api-1.6.1.jar
@@ -199,20 +206,11 @@
 - ojdbc6.jar under the OTN Development and Distribution
   License Agreement (in /legal folder and available at
   http://www.oracle.com/technology/software/popup-license/distribution-license.html)
-- hibernate-jpa-2.0-api-1.0.0.Final.jar
-  License Agreement available at:
-  http://fisheye.jboss.org/browse/Hibernate/jpa-api/tags/hibernate-jpa-2.0-api-1.0.0.Final/license.txt?r=16109&r=16109
 
 # jaxrpc.jar
 All files under the corresponding Sun Binary Code License. This is not free
 software, but provided under license from Sun Microsystems.
 
-# jta.jar. This software is subject to the Sun License Agreement and terms
-  set out in /legal/jta/ directory and also available at
-  https://cds.sun.com/is-bin/INTERSHOP.enfinity/WFS/CDS-CDS_Developer-Site/en_US/-/USD/ViewLicense-Start?LicenseUUID=aanACUFBI3YAAAEY1Z45AXiO&ProductUUID=gp_ACUFBpawAAAEYhHY5AXub
-Note: the software marked Java, JAVAX or Sun may not be modified in any
-way.
-
 # ejb-api-3.0.jar
 # jboss-interceptor-api-3.1.0-CR3.jar
 # jboss-ejb3-api-3.1.0.jar
@@ -228,6 +226,7 @@
 # javax.inject.jar
 # jboss-interceptor-core-2.0.0.CR1.jar
 # jboss-interceptor-spi-2.0.0.CR1.jar
+# jboss-logging-3.3.2.Final.jar
 # weld-api.jar
 # weld-core-1.1.24.Final.jar
 # weld-servlet-core-1.1.24.Final.jar
@@ -262,13 +261,20 @@
 # guice-2.0.jar
 # tomcat-juli.jar
 # tomcat-jdbc.jar
+# classmate-1.3.4.jar
+# jandex-2.0.5.Final.jar
 Under the Apache 2.0 license (included as Apache_license-2.0.txt in this folder)
 
+# byte-buddy-1.8.12.jar
+Under the Apache 2.0 license (included as Apache_license-2.0.txt in this folder),
+note that Byte Buddy depends on the ASM library which is distributed under a BSD license (included as ASM_BSD_license.txt in this folder)
+
 # jslint4java-1.4.7.jar
 Under the New BSD license (available at http://www.opensource.org/licenses/bsd-license.php)
 
 # javax.annotation-api-1.2.jar
 # javax.xml.soap-api-1.3.7.jar
+# jboss-transaction-api_1.2_spec-1.1.1.Final.jar
 Under the CDDL license version 1.0 (license available at https://spdx.org/licenses/CDDL-1.0.html 
 or in the file CDDL-1.0.txt in this folder)
 
Binary file lib/runtime/byte-buddy-1.8.12.jar has changed
Binary file lib/runtime/classmate-1.3.4.jar has changed
Binary file lib/runtime/hibernate-commons-annotations-5.0.4.Final.jar has changed
Binary file lib/runtime/hibernate-core-5.3.2.Final.jar has changed
Binary file lib/runtime/hibernate-jpa-2.0-api-1.0.0.Final.jar has changed
Binary file lib/runtime/hibernate3-patched.jar has changed
Binary file lib/runtime/jandex-2.0.5.Final.jar has changed
Binary file lib/runtime/javassist-3.20.0-GA.jar has changed
Binary file lib/runtime/javassist-3.22.0-GA.jar has changed
Binary file lib/runtime/javax.persistence-api-2.2.jar has changed
Binary file lib/runtime/jboss-logging-3.3.2.Final.jar has changed
Binary file lib/runtime/jboss-transaction-api_1.2_spec-1.1.1.Final.jar has changed
Binary file lib/runtime/jta.jar has changed
--- a/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/ad_actionbutton/AddPaymentFromTransaction.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/ad_actionbutton/AddPaymentFromTransaction.java	Tue Jul 24 10:44:21 2018 +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-2013 Openbravo SLU
+ * All portions are Copyright (C) 2010-2018 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s): Enterprise Intelligence Systems (http://www.eintel.com.au).
  *************************************************************************
@@ -907,7 +907,7 @@
       obCriteria.add(Restrictions.eq(Preference.PROPERTY_ATTRIBUTE, "Doubtful_Debt_Visibility"));
       obCriteria.add(Restrictions.eq(Preference.PROPERTY_CLIENT, OBContext.getOBContext()
           .getCurrentClient()));
-      obCriteria.add(Restrictions.in(Preference.PROPERTY_ORGANIZATION + ".id", OBContext
+      obCriteria.add(Restrictions.in(Preference.PROPERTY_ORGANIZATION + ".id", (Object[]) OBContext
           .getOBContext().getReadableOrganizations()));
       Preference preference = (Preference) obCriteria.uniqueResult();
       if (preference != null) {
--- a/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/ad_reports/ReportReconciliation.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/ad_reports/ReportReconciliation.java	Tue Jul 24 10:44:21 2018 +0200
@@ -33,6 +33,7 @@
 import org.hibernate.criterion.ProjectionList;
 import org.hibernate.criterion.Projections;
 import org.hibernate.criterion.Restrictions;
+import org.hibernate.sql.JoinType;
 import org.openbravo.advpaymentmngt.dao.MatchTransactionDao;
 import org.openbravo.base.secureApp.HttpSecureAppServlet;
 import org.openbravo.base.secureApp.VariablesSecureApp;
@@ -251,7 +252,7 @@
           FIN_BankStatementLine.class);
       obcBsl.createAlias(FIN_BankStatementLine.PROPERTY_BANKSTATEMENT, "bs");
       obcBsl.createAlias(FIN_BankStatementLine.PROPERTY_FINANCIALACCOUNTTRANSACTION, "tr",
-          OBCriteria.LEFT_JOIN);
+          JoinType.LEFT_OUTER_JOIN);
       obcBsl.add(Restrictions.le(FIN_BankStatementLine.PROPERTY_TRANSACTIONDATE,
           recon.getEndingDate()));
       List<FIN_Reconciliation> afterReconciliations = MatchTransactionDao
--- a/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/dao/AdvPaymentMngtDao.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/dao/AdvPaymentMngtDao.java	Tue Jul 24 10:44:21 2018 +0200
@@ -30,13 +30,13 @@
 import java.util.Set;
 
 import org.apache.commons.lang.StringUtils;
-import org.hibernate.Query;
 import org.hibernate.Session;
 import org.hibernate.criterion.Criterion;
 import org.hibernate.criterion.DetachedCriteria;
 import org.hibernate.criterion.Projections;
 import org.hibernate.criterion.Restrictions;
 import org.hibernate.criterion.Subqueries;
+import org.hibernate.query.Query;
 import org.openbravo.advpaymentmngt.APRMPendingPaymentFromInvoice;
 import org.openbravo.advpaymentmngt.utility.FIN_Utility;
 import org.openbravo.advpaymentmngt.utility.Value;
@@ -272,7 +272,7 @@
       obc.add(Restrictions.isNotNull(FIN_PaymentPropDetail.PROPERTY_FINPAYMENTSCHEDULEDETAIL));
       List<FIN_PaymentPropDetail> paymentPropDetailList = obc.list();
       if (paymentPropDetailList != null && !paymentPropDetailList.isEmpty()) {
-        List<FIN_PaymentScheduleDetail> aux = new ArrayList<FIN_PaymentScheduleDetail>();
+        List<FIN_PaymentScheduleDetail> aux = new ArrayList<>();
         for (FIN_PaymentPropDetail ppd : paymentPropDetailList) {
           aux.add(ppd.getFINPaymentScheduledetail());
         }
@@ -1487,7 +1487,7 @@
         .getOrganizationStructureProvider().getNaturalTree(strOrgId)));
     obc.setFilterOnReadableOrganization(false);
 
-    List<String> payMethods = new ArrayList<String>();
+    List<String> payMethods = new ArrayList<>();
     if (strFinancialAccountId != null && !strFinancialAccountId.isEmpty()) {
       for (FinAccPaymentMethod finAccPayMethod : getObject(FIN_FinancialAccount.class,
           strFinancialAccountId).getFinancialMgmtFinAccPaymentMethodList()) {
@@ -1671,7 +1671,7 @@
     private int MAX = 999;
 
     private Criterion compoundexp = null;
-    List<String> finAccs = new ArrayList<String>();
+    List<String> finAccs = new ArrayList<>();
 
     public void addFinAccPaymentMethod(FinAccPaymentMethod finAccPayMethod) {
       finAccs.add(finAccPayMethod.getAccount().getId());
@@ -1694,7 +1694,7 @@
       } else {
         compoundexp = Restrictions.or(compoundexp, Restrictions.in("id", finAccs));
       }
-      finAccs = new ArrayList<String>();
+      finAccs = new ArrayList<>();
     }
   }
 
@@ -1777,7 +1777,7 @@
   }
 
   public List<FIN_Payment> getPaymentProposalPayments(FIN_PaymentProposal paymentProposal) {
-    List<FIN_Payment> paymentsInProposal = new ArrayList<FIN_Payment>();
+    List<FIN_Payment> paymentsInProposal = new ArrayList<>();
     for (FIN_PaymentPropDetail proposalDetail : paymentProposal.getFINPaymentPropDetailList())
       if ("RPAE".equals(proposalDetail.getFINPaymentScheduledetail().getPaymentDetails()
           .getFinPayment().getStatus()))
@@ -1817,7 +1817,7 @@
       String financialAccountId, Date dateFrom, Date dateTo, int offset, int pageSize,
       String strOrderByProperty, String strAscDesc, boolean isReceipt) {
 
-    List<FIN_Payment> emptyList = new ArrayList<FIN_Payment>();
+    List<FIN_Payment> emptyList = new ArrayList<>();
     if (organizationId == null || organizationId.isEmpty()) {
       return emptyList;
     }
@@ -1858,7 +1858,7 @@
   }
 
   public List<FIN_Payment> getPendingExecutionPayments(String strInvoiceId) {
-    List<FIN_Payment> payments = new ArrayList<FIN_Payment>();
+    List<FIN_Payment> payments = new ArrayList<>();
     List<FIN_PaymentSchedule> paySchedList = new AdvPaymentMngtDao().getObject(Invoice.class,
         strInvoiceId).getFINPaymentScheduleList();
     OBCriteria<FIN_PaymentScheduleDetail> psdCriteria = OBDal.getInstance().createCriteria(
@@ -2011,12 +2011,11 @@
       params.put("orgIds", orgIds);
 
       final Session session = OBDal.getInstance().getSession();
-      final Query query = session.createQuery(hql.toString());
+      final Query<FIN_Payment> query = session.createQuery(hql.toString(), FIN_Payment.class);
       query.setProperties(params);
 
-      @SuppressWarnings("unchecked")
       final List<FIN_Payment> queryList = query.list();
-      final List<FIN_Payment> paymentList = new ArrayList<FIN_Payment>();
+      final List<FIN_Payment> paymentList = new ArrayList<>();
       for (FIN_Payment fp : queryList) {
         if ((FIN_Utility.seqnumberpaymentstatus(fp.getStatus())) >= (FIN_Utility
             .seqnumberpaymentstatus(FIN_Utility.invoicePaymentStatus(fp)))) {
@@ -2142,7 +2141,7 @@
    * 
    */
   public boolean isPaymentMadeStatus(String paymentStatus) {
-    ArrayList<String> paidStatusList = new ArrayList<String>();
+    ArrayList<String> paidStatusList = new ArrayList<>();
     paidStatusList.add(PAYMENT_STATUS_PAYMENT_CLEARED);
     paidStatusList.add(PAYMENT_STATUS_DEPOSIT_NOT_CLEARED);
     paidStatusList.add(PAYMENT_STATUS_PAYMENT_MADE);
--- a/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/dao/MatchTransactionDao.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/dao/MatchTransactionDao.java	Tue Jul 24 10:44:21 2018 +0200
@@ -28,12 +28,13 @@
 
 import javax.servlet.ServletException;
 
-import org.hibernate.Query;
 import org.hibernate.Session;
 import org.hibernate.criterion.Order;
 import org.hibernate.criterion.ProjectionList;
 import org.hibernate.criterion.Projections;
 import org.hibernate.criterion.Restrictions;
+import org.hibernate.query.Query;
+import org.hibernate.sql.JoinType;
 import org.openbravo.base.provider.OBProvider;
 import org.openbravo.base.secureApp.VariablesSecureApp;
 import org.openbravo.base.structure.BaseOBObject;
@@ -507,7 +508,7 @@
           FIN_BankStatementLine.class);
       obcBsl.createAlias(FIN_BankStatementLine.PROPERTY_BANKSTATEMENT, "bs");
       obcBsl.createAlias(FIN_BankStatementLine.PROPERTY_FINANCIALACCOUNTTRANSACTION, "tr",
-          OBCriteria.LEFT_JOIN);
+          JoinType.LEFT_OUTER_JOIN);
       obcBsl.add(Restrictions.or(
           Restrictions.isNull(FIN_BankStatementLine.PROPERTY_FINANCIALACCOUNTTRANSACTION),
           Restrictions.eq("tr." + FIN_FinaccTransaction.PROPERTY_RECONCILIATION, reconciliation)));
@@ -553,7 +554,7 @@
           FIN_BankStatementLine.class);
       obcBsl.createAlias(FIN_BankStatementLine.PROPERTY_BANKSTATEMENT, "bs");
       obcBsl.createAlias(FIN_BankStatementLine.PROPERTY_FINANCIALACCOUNTTRANSACTION, "tr",
-          OBCriteria.LEFT_JOIN);
+          JoinType.LEFT_OUTER_JOIN);
 
       List<FIN_Reconciliation> afterReconciliations = getReconciliationListAfterDate(lastReconciliation);
       if (afterReconciliations.size() > 0) {
@@ -638,10 +639,10 @@
           .append(" and not exists (select 1 from FIN_BankStatementLine as bsl where bsl.financialAccountTransaction = e)");
       hqlString.append(" and e.transactionDate <= :date");
       final Session session = OBDal.getInstance().getSession();
-      final Query query = session.createQuery(hqlString.toString());
+      final Query<BigDecimal> query = session.createQuery(hqlString.toString(), BigDecimal.class);
       query.setParameter("account", reconciliation.getAccount().getId());
       query.setParameter("date", reconciliation.getEndingDate());
-      total = (BigDecimal) query.uniqueResult();
+      total = query.uniqueResult();
     } finally {
       OBContext.restorePreviousMode();
     }
@@ -656,7 +657,7 @@
           FIN_BankStatementLine.class);
       obcBsl.createAlias(FIN_BankStatementLine.PROPERTY_BANKSTATEMENT, "bs");
       obcBsl.createAlias(FIN_BankStatementLine.PROPERTY_FINANCIALACCOUNTTRANSACTION, "tr",
-          OBCriteria.LEFT_JOIN);
+          JoinType.LEFT_OUTER_JOIN);
       obcBsl.add(Restrictions.eq("bs." + FIN_BankStatement.PROPERTY_ACCOUNT,
           reconciliation.getAccount()));
       obcBsl.add(Restrictions.eq("bs." + FIN_BankStatement.PROPERTY_PROCESSED, true));
--- a/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/dao/TransactionsDao.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/dao/TransactionsDao.java	Tue Jul 24 10:44:21 2018 +0200
@@ -26,9 +26,9 @@
 import java.util.List;
 import java.util.Map;
 
-import org.hibernate.Query;
 import org.hibernate.Session;
 import org.hibernate.criterion.Restrictions;
+import org.hibernate.query.Query;
 import org.openbravo.advpaymentmngt.utility.FIN_Utility;
 import org.openbravo.base.exception.OBException;
 import org.openbravo.base.provider.OBProvider;
@@ -145,13 +145,14 @@
   }
 
   public static Long getTransactionMaxLineNo(FIN_FinancialAccount financialAccount) {
-    Query query = OBDal
+    Query<Long> query = OBDal
         .getInstance()
         .getSession()
         .createQuery(
-            "select max(f.lineNo) as maxLineno from FIN_Finacc_Transaction as f where account.id=:accountId");
+            "select max(f.lineNo) as maxLineno from FIN_Finacc_Transaction as f where account.id=:accountId",
+            Long.class);
     query.setParameter("accountId", financialAccount.getId());
-    Long maxLineNo = (Long) query.uniqueResult();
+    Long maxLineNo = query.uniqueResult();
     if (maxLineNo != null) {
       return maxLineNo;
     }
@@ -385,14 +386,11 @@
     hqlString.append(" and ft.processed = 'Y'");
 
     final Session session = OBDal.getInstance().getSession();
-    final Query query = session.createQuery(hqlString.toString());
-
-    for (Object resultObject : query.list()) {
-      if (resultObject != null && resultObject.getClass().isInstance(BigDecimal.ONE)) {
-        return (BigDecimal) resultObject;
-      }
+    final Query<BigDecimal> query = session.createQuery(hqlString.toString(), BigDecimal.class);
+    BigDecimal resultObject = query.uniqueResult();
+    if (resultObject != null) {
+      return resultObject;
     }
-
     return BigDecimal.ZERO;
   }
 }
--- a/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/event/FIN_PaymentEventListener.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/event/FIN_PaymentEventListener.java	Tue Jul 24 10:44:21 2018 +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) 2012-2016 Openbravo SLU
+ * All portions are Copyright (C) 2012-2018 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  *************************************************************************
@@ -24,7 +24,7 @@
 import javax.enterprise.event.Observes;
 
 import org.apache.commons.lang.StringUtils;
-import org.hibernate.Query;
+import org.hibernate.query.Query;
 import org.openbravo.advpaymentmngt.dao.AdvPaymentMngtDao;
 import org.openbravo.base.exception.OBException;
 import org.openbravo.base.model.Entity;
@@ -179,9 +179,10 @@
     hql.append("where paymentExecutionProcess.id <> :paymentExecutionProcessId ");
     hql.append("and payment.id = :paymentId ");
 
+    @SuppressWarnings("rawtypes")
     Query updateQry = OBDal.getInstance().getSession().createQuery(hql.toString());
-    updateQry.setString("paymentExecutionProcessId", executionProcess.getId());
-    updateQry.setString("paymentId", payment.getId());
+    updateQry.setParameter("paymentExecutionProcessId", executionProcess.getId());
+    updateQry.setParameter("paymentId", payment.getId());
     rowCount = updateQry.executeUpdate();
     return rowCount;
   }
@@ -201,8 +202,9 @@
     hql.append("delete from APRM_PendingPaymentInvoice ");
     hql.append("where payment.id = :paymentId ");
 
+    @SuppressWarnings("rawtypes")
     Query updateQry = OBDal.getInstance().getSession().createQuery(hql.toString());
-    updateQry.setString("paymentId", payment.getId());
+    updateQry.setParameter("paymentId", payment.getId());
     rowCount = updateQry.executeUpdate();
     return rowCount;
   }
--- a/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/event/FIN_ReconciliationEventListener.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/event/FIN_ReconciliationEventListener.java	Tue Jul 24 10:44:21 2018 +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) 2016 Openbravo SLU
+ * All portions are Copyright (C) 2016-2018 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  *************************************************************************
@@ -22,7 +22,7 @@
 
 import javax.enterprise.event.Observes;
 
-import org.hibernate.Query;
+import org.hibernate.query.Query;
 import org.openbravo.base.model.Entity;
 import org.openbravo.base.model.ModelProvider;
 import org.openbravo.client.kernel.event.EntityDeleteEvent;
@@ -39,8 +39,7 @@
     return entities;
   }
 
-  public void onDelete(@Observes
-  EntityDeleteEvent event) {
+  public void onDelete(@Observes EntityDeleteEvent event) {
     if (!isValidEvent(event)) {
       return;
     }
@@ -68,10 +67,11 @@
         + FIN_Reconciliation.PROPERTY_ENDINGBALANCE + " - :balance");
     update.append(" where " + FIN_Reconciliation.PROPERTY_ACCOUNT + ".id = :accountId");
     update.append(" and " + FIN_Reconciliation.PROPERTY_TRANSACTIONDATE + " > :date");
+    @SuppressWarnings("rawtypes")
     Query updateQry = OBDal.getInstance().getSession().createQuery(update.toString());
-    updateQry.setBigDecimal("balance", balance);
-    updateQry.setString("accountId", rec.getAccount().getId());
-    updateQry.setTimestamp("date", rec.getTransactionDate());
+    updateQry.setParameter("balance", balance);
+    updateQry.setParameter("accountId", rec.getAccount().getId());
+    updateQry.setParameter("date", rec.getTransactionDate());
     updateQry.executeUpdate();
   }
 }
--- a/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/filterexpression/AddOrderOrInvoiceFilterExpressionHandler.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/filterexpression/AddOrderOrInvoiceFilterExpressionHandler.java	Tue Jul 24 10:44:21 2018 +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) 2014 Openbravo SLU
+ * All portions are Copyright (C) 2014-2018 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -28,8 +28,8 @@
 import org.apache.commons.lang.StringUtils;
 import org.codehaus.jettison.json.JSONException;
 import org.codehaus.jettison.json.JSONObject;
-import org.hibernate.Query;
 import org.hibernate.Session;
+import org.hibernate.query.Query;
 import org.openbravo.client.application.OBBindingsConstants;
 import org.openbravo.client.kernel.ComponentProvider;
 import org.openbravo.dal.service.OBDal;
@@ -107,10 +107,10 @@
     hqlString.append(" group by coalesce(ipspm, opspm)");
 
     final Session session = OBDal.getInstance().getSession();
-    final Query query = session.createQuery(hqlString.toString());
+    final Query<String> query = session.createQuery(hqlString.toString(), String.class);
     query.setParameter("paymentId", paymentId);
     FIN_Payment payment = OBDal.getInstance().get(FIN_Payment.class, paymentId);
-    for (Object pmId : query.list()) {
+    for (String pmId : query.list()) {
       if (!payment.getPaymentMethod().getId().equals(pmId)) {
         return true;
       }
--- a/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/filterexpression/FundsTransferGLItemDefaultValueExpression.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/filterexpression/FundsTransferGLItemDefaultValueExpression.java	Tue Jul 24 10:44:21 2018 +0200
@@ -23,7 +23,7 @@
 import org.apache.commons.lang.StringUtils;
 import org.codehaus.jettison.json.JSONException;
 import org.codehaus.jettison.json.JSONObject;
-import org.hibernate.Query;
+import org.hibernate.query.Query;
 import org.openbravo.client.application.FilterExpression;
 import org.openbravo.dal.core.OBContext;
 import org.openbravo.dal.service.OBDal;
@@ -91,10 +91,11 @@
     hql.append(" and p.aPRMGlitem is not null ");
     hql.append(" order by t.levelno asc ");
 
-    Query query = OBDal.getInstance().getSession().createQuery(hql.toString());
+    Query<GLItem> query = OBDal.getInstance().getSession()
+        .createQuery(hql.toString(), GLItem.class);
     query.setParameter("organizationId", organization.getId());
     query.setMaxResults(1);
-    final GLItem glItem = (GLItem) query.uniqueResult();
+    final GLItem glItem = query.uniqueResult();
     return glItem != null ? glItem.getId() : null;
   }
 
--- a/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/process/FIN_AddPayment.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/process/FIN_AddPayment.java	Tue Jul 24 10:44:21 2018 +0200
@@ -33,10 +33,10 @@
 
 import javax.servlet.ServletException;
 
-import org.hibernate.Query;
 import org.hibernate.Session;
 import org.hibernate.criterion.Projections;
 import org.hibernate.criterion.Restrictions;
+import org.hibernate.query.Query;
 import org.openbravo.advpaymentmngt.dao.AdvPaymentMngtDao;
 import org.openbravo.advpaymentmngt.utility.FIN_Utility;
 import org.openbravo.base.exception.OBException;
@@ -1481,7 +1481,6 @@
    * @param paymentProposal
    * @return List of payment identifiers
    */
-  @SuppressWarnings("unchecked")
   public static List<String> getPaymentFromPaymentProposal(FIN_PaymentProposal paymentProposal) {
     // FIXME: added to access the FIN_PaymentSchedule and FIN_PaymentScheduleDetail tables to be
     // removed when new security implementation is done
@@ -1497,7 +1496,7 @@
       hql.append("inner join pd." + FIN_PaymentDetail.PROPERTY_FINPAYMENT + " as p ");
       hql.append("WHERE ppd." + FIN_PaymentPropDetail.PROPERTY_FINPAYMENTPROPOSAL + "."
           + FIN_PaymentProposal.PROPERTY_ID + "= :paymentProposalId");
-      final Query obqPay = session.createQuery(hql.toString());
+      final Query<String> obqPay = session.createQuery(hql.toString(), String.class);
       obqPay.setParameter("paymentProposalId", paymentProposal.getId());
 
       return obqPay.list();
--- a/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/process/FIN_AddPaymentFromJournalLine.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/process/FIN_AddPaymentFromJournalLine.java	Tue Jul 24 10:44:21 2018 +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-2016 Openbravo SLU
+ * All portions are Copyright (C) 2013-2018 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  *************************************************************************
@@ -24,13 +24,14 @@
 import java.util.Date;
 import java.util.List;
 
-import org.hibernate.Query;
 import org.hibernate.Session;
+import org.hibernate.query.Query;
 import org.openbravo.advpaymentmngt.dao.AdvPaymentMngtDao;
 import org.openbravo.advpaymentmngt.utility.FIN_Utility;
 import org.openbravo.base.exception.OBException;
 import org.openbravo.dal.core.OBContext;
 import org.openbravo.dal.service.OBDal;
+import org.openbravo.erpCommon.ad_forms.AcctSchema;
 import org.openbravo.erpCommon.utility.OBError;
 import org.openbravo.model.common.businesspartner.BusinessPartner;
 import org.openbravo.model.common.enterprise.DocumentType;
@@ -81,7 +82,8 @@
               + "', o.id, o.client) <> -1 ");
           hsqlScript.append("and o.generalLedger is not null ");
           final Session session = OBDal.getInstance().getSession();
-          final Query query = session.createQuery(hsqlScript.toString());
+          final Query<AcctSchema> query = session.createQuery(hsqlScript.toString(),
+              AcctSchema.class);
           if (query.list().size() != 1) {
             throw new OBException("@FIN_NoMultiAccountingAllowed@");
           }
--- a/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/process/FIN_TransactionProcess.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/process/FIN_TransactionProcess.java	Tue Jul 24 10:44:21 2018 +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-2017 Openbravo SLU
+ * All portions are Copyright (C) 2010-2018 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  *************************************************************************
@@ -23,9 +23,9 @@
 
 import org.apache.commons.lang.StringUtils;
 import org.hibernate.LockOptions;
-import org.hibernate.Query;
 import org.hibernate.Session;
 import org.hibernate.criterion.Restrictions;
+import org.hibernate.query.Query;
 import org.openbravo.advpaymentmngt.APRM_FinaccTransactionV;
 import org.openbravo.advpaymentmngt.dao.AdvPaymentMngtDao;
 import org.openbravo.advpaymentmngt.utility.FIN_Utility;
@@ -373,12 +373,13 @@
     StringBuilder queryStr = new StringBuilder(
         "select a from FIN_Financial_Account a where id = :id");
     final Session session = OBDal.getInstance().getSession();
-    final Query query = session.createQuery(queryStr.toString());
+    final Query<FIN_FinancialAccount> query = session.createQuery(queryStr.toString(),
+        FIN_FinancialAccount.class);
     query.setParameter("id", account.getId());
     query.setMaxResults(1);
     query.setLockOptions(LockOptions.UPGRADE);
     OBDal.getInstance().getSession().evict(account);
-    return (FIN_FinancialAccount) query.uniqueResult();
+    return query.uniqueResult();
   }
 
 }
--- a/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/process/RecordID2Filling.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/process/RecordID2Filling.java	Tue Jul 24 10:44:21 2018 +0200
@@ -1,14 +1,32 @@
+/*
+ *************************************************************************
+ * The contents of this file are subject to the Openbravo  Public  License
+ * Version  1.0  (the  "License"),  being   the  Mozilla   Public  License
+ * Version 1.1  with a permitted attribution clause; you may not  use this
+ * file except in compliance with the License. You  may  obtain  a copy of
+ * the License at http://www.openbravo.com/legal/license.html
+ * Software distributed under the License  is  distributed  on  an "AS IS"
+ * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
+ * License for the specific  language  governing  rights  and  limitations
+ * 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 Rights Reserved.
+ * Contributor(s):  ______________________________________.
+ *************************************************************************
+ */
 package org.openbravo.advpaymentmngt.process;
 
 import java.util.HashSet;
 import java.util.List;
 import java.util.Set;
 
-import org.hibernate.Query;
 import org.hibernate.ScrollMode;
 import org.hibernate.ScrollableResults;
 import org.hibernate.Session;
 import org.hibernate.criterion.Restrictions;
+import org.hibernate.query.Query;
 import org.openbravo.dal.core.OBContext;
 import org.openbravo.dal.service.OBCriteria;
 import org.openbravo.dal.service.OBDal;
@@ -51,9 +69,8 @@
         .append("   and exists (select 1 from FIN_Payment_Schedule as ps where ps.id = f.lineID)");
     hqlInvoices.append("   and f.account.id in :accounts");
     hqlInvoices.append("   and f.recordID2 is null");
-    Query updateInvoices = OBDal.getInstance().getSession().createQuery(hqlInvoices.toString());
-    updateInvoices.setParameterList("accounts", bpAccounts);
-    int numberInvoices = updateInvoices.executeUpdate();
+    int numberInvoices = OBDal.getInstance().getSession().createQuery(hqlInvoices.toString())
+        .setParameterList("accounts", bpAccounts).executeUpdate();
     logger.logln("Number of invoice entries updated: " + numberInvoices);
     OBDal.getInstance().flush();
 
@@ -66,9 +83,8 @@
     hqlPayments.append("where f.table.id = 'D1A97202E832470285C9B1EB026D54E2' ");
     hqlPayments.append(" and f.account.id in :accounts");
     hqlPayments.append(" and f.recordID2 is null");
-    Query updatePayments = OBDal.getInstance().getSession().createQuery(hqlPayments.toString());
-    updatePayments.setParameterList("accounts", bpAccounts);
-    int numberPayments = updatePayments.executeUpdate();
+    int numberPayments = OBDal.getInstance().getSession().createQuery(hqlPayments.toString())
+        .setParameterList("accounts", bpAccounts).executeUpdate();
 
     logger.logln("Number of payment entries updated: " + numberPayments);
     OBDal.getInstance().flush();
@@ -82,9 +98,8 @@
     hqlPaymentsInTransit
         .append(" and exists (select 1 from FIN_Payment as p where p.id = f.recordID "
             + "and not exists( select 1 from FIN_Payment_Credit as pc where pc.creditPaymentUsed = p))");
-    Query updatePaymentsinTransit = OBDal.getInstance().getSession()
-        .createQuery(hqlPaymentsInTransit.toString());
-    int numberPaymentsInTransit = updatePaymentsinTransit.executeUpdate();
+    int numberPaymentsInTransit = OBDal.getInstance().getSession()
+        .createQuery(hqlPaymentsInTransit.toString()).executeUpdate();
 
     logger.logln("Number of payment entries updated (In Transit): " + numberPaymentsInTransit);
     OBDal.getInstance().flush();
@@ -95,7 +110,8 @@
     hqlTrxRec
         .append("   and exists (select 1 from FIN_Finacc_Transaction as t where t.id = f.lineID)");
     hqlTrxRec.append("   and account.id in :accounts");
-    Query query = OBDal.getInstance().getSession().createQuery(hqlTrxRec.toString());
+    Query<AccountingFact> query = OBDal.getInstance().getSession()
+        .createQuery(hqlTrxRec.toString(), AccountingFact.class);
 
     query.setParameterList("accounts", bpAccounts);
     int i = 0;
@@ -161,8 +177,8 @@
         .append("   and (exists (select 1 from FIN_Finacc_Transaction as t where t.id = f.lineID) or (f.lineID is null and f.table.id = '"
             + TRANSACTION_TABLE_ID + "'))");
     hqlTrxRecInTransit.append("   and account.id in :accounts");
-    Query queryInTransit = OBDal.getInstance().getSession()
-        .createQuery(hqlTrxRecInTransit.toString());
+    Query<AccountingFact> queryInTransit = OBDal.getInstance().getSession()
+        .createQuery(hqlTrxRecInTransit.toString(), AccountingFact.class);
 
     queryInTransit.setParameterList("accounts", faAccounts);
     i = 0;
@@ -238,9 +254,8 @@
         .append(" where exists (select 1 from FinancialMgmtAccountingFact as f3 "
             + "where f3.recordID2 = f.recordID2 and f3.accountingSchema = f.accountingSchema and f3.account = f.account group by f3.recordID2 having sum(f3.credit-f3.debit)=0)");
     hqlDateBalanced.append(" and f.dateBalanced is null");
-    Query updateDateBalanced = OBDal.getInstance().getSession()
-        .createQuery(hqlDateBalanced.toString());
-    int numberBalanced = updateDateBalanced.executeUpdate();
+    int numberBalanced = OBDal.getInstance().getSession().createQuery(hqlDateBalanced.toString())
+        .executeUpdate();
     logger.logln("Number of date balanced entries: " + numberBalanced);
     OBDal.getInstance().flush();
   }
@@ -285,7 +300,7 @@
   }
 
   private Set<String> getBPAccountList(boolean isReceipt, String acctSchemaId) {
-    Set<String> result = new HashSet<String>();
+    Set<String> result = new HashSet<>();
     final StringBuilder hqlString = new StringBuilder();
     if (isReceipt) {
       hqlString.append("select distinct ca.customerReceivablesNo, ca.customerPrepayment");
@@ -297,14 +312,11 @@
       hqlString.append(" where va.accountingSchema.id = '" + acctSchemaId + "'");
     }
     final Session session = OBDal.getInstance().getSession();
-    final Query query = session.createQuery(hqlString.toString());
-    for (Object resultObject : query.list()) {
-      if (resultObject.getClass().isArray()) {
-        final Object[] values = (Object[]) resultObject;
-        for (Object value : values) {
-          if (value instanceof AccountingCombination) {
-            result.add(((AccountingCombination) value).getAccount().getId());
-          }
+    final Query<Object[]> query = session.createQuery(hqlString.toString(), Object[].class);
+    for (Object[] values : query.list()) {
+      for (Object value : values) {
+        if (value instanceof AccountingCombination) {
+          result.add(((AccountingCombination) value).getAccount().getId());
         }
       }
     }
@@ -312,7 +324,7 @@
   }
 
   private Set<String> getFAAccountList(boolean isReceipt, String acctSchemaId) {
-    Set<String> result = new HashSet<String>();
+    Set<String> result = new HashSet<>();
     final StringBuilder hqlString = new StringBuilder();
     if (isReceipt) {
       hqlString.append("select distinct faa.inTransitPaymentAccountIN");
@@ -322,21 +334,11 @@
     hqlString.append(" from FIN_Financial_Account_Acct as faa");
     hqlString.append(" where faa.accountingSchema.id = :acctSchemaId");
     final Session session = OBDal.getInstance().getSession();
-    final Query query = session.createQuery(hqlString.toString());
+    final Query<AccountingCombination> query = session.createQuery(hqlString.toString(),
+        AccountingCombination.class);
     query.setParameter("acctSchemaId", acctSchemaId);
-    for (Object resultObject : query.list()) {
-      if (resultObject.getClass().isArray()) {
-        final Object[] values = (Object[]) resultObject;
-        for (Object value : values) {
-          if (value instanceof AccountingCombination) {
-            result.add(((AccountingCombination) value).getAccount().getId());
-          }
-        }
-      } else {
-        if (resultObject instanceof AccountingCombination) {
-          result.add(((AccountingCombination) resultObject).getAccount().getId());
-        }
-      }
+    for (AccountingCombination value : query.list()) {
+      result.add(value.getAccount().getId());
     }
     final StringBuilder hqlString2 = new StringBuilder();
     if (isReceipt) {
@@ -346,29 +348,18 @@
     }
     hqlString2.append(" from FIN_Financial_Account_Acct as faa");
     hqlString2.append(" where faa.accountingSchema.id = :acctSchemaId");
-    // session = OBDal.getInstance().getSession();
-    final Query query2 = session.createQuery(hqlString2.toString());
+    final Query<AccountingCombination> query2 = session.createQuery(hqlString2.toString(),
+        AccountingCombination.class);
     query2.setParameter("acctSchemaId", acctSchemaId);
-    for (Object resultObject : query2.list()) {
-      if (resultObject.getClass().isArray()) {
-        final Object[] values = (Object[]) resultObject;
-        for (Object value : values) {
-          if (value instanceof AccountingCombination) {
-            result.add(((AccountingCombination) value).getAccount().getId());
-          }
-        }
-      } else {
-        if (resultObject instanceof AccountingCombination) {
-          result.add(((AccountingCombination) resultObject).getAccount().getId());
-        }
-      }
+    for (AccountingCombination value : query2.list()) {
+      result.add(value.getAccount().getId());
     }
     return result;
   }
 
   private Set<String> getFAAccountList(boolean isReceipt, String acctSchemaId,
       String financialAccountId, String paymentMethodId, String table) {
-    Set<String> result = new HashSet<String>();
+    Set<String> result = new HashSet<>();
     final StringBuilder hqlString = new StringBuilder();
     String use = null;
     if (paymentMethodId != null && !"".equals(paymentMethodId)) {
@@ -406,7 +397,7 @@
       hqlString.append(" and faa.account.id = :financialAccountId");
     }
     final Session session = OBDal.getInstance().getSession();
-    final Query query = session.createQuery(hqlString.toString());
+    final Query<Object> query = session.createQuery(hqlString.toString(), Object.class);
     query.setParameter("acctSchemaId", acctSchemaId);
     if (financialAccountId != null && !"".equals(financialAccountId)) {
       query.setParameter("financialAccountId", financialAccountId);
--- a/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/utility/FIN_BankStatementImport.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/utility/FIN_BankStatementImport.java	Tue Jul 24 10:44:21 2018 +0200
@@ -32,10 +32,10 @@
 import org.apache.commons.fileupload.FileItem;
 import org.apache.commons.lang.StringUtils;
 import org.apache.log4j.Logger;
-import org.hibernate.Query;
 import org.hibernate.ScrollMode;
 import org.hibernate.ScrollableResults;
 import org.hibernate.criterion.Restrictions;
+import org.hibernate.query.Query;
 import org.openbravo.advpaymentmngt.dao.AdvPaymentMngtDao;
 import org.openbravo.advpaymentmngt.process.FIN_AddPayment;
 import org.openbravo.base.exception.OBException;
@@ -414,7 +414,8 @@
       whereClause.append(" and b." + BusinessPartner.PROPERTY_ORGANIZATION + ".id in (");
       whereClause.append(Utility.getInStrSet(new OrganizationStructureProvider()
           .getNaturalTree(organization.getId())) + ") ");
-      final Query bl = OBDal.getInstance().getSession().createQuery(whereClause.toString());
+      final Query<Object[]> bl = OBDal.getInstance().getSession()
+          .createQuery(whereClause.toString(), Object[].class);
       businessPartnersScroll = bl.scroll(ScrollMode.SCROLL_SENSITIVE);
 
       if (!businessPartnersScroll.next()) {
--- a/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/utility/FIN_Utility.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/utility/FIN_Utility.java	Tue Jul 24 10:44:21 2018 +0200
@@ -37,9 +37,9 @@
 import org.apache.commons.lang.StringUtils;
 import org.apache.commons.lang.time.DateUtils;
 import org.hibernate.LockOptions;
-import org.hibernate.Query;
 import org.hibernate.Session;
 import org.hibernate.criterion.Restrictions;
+import org.hibernate.query.Query;
 import org.openbravo.advpaymentmngt.dao.AdvPaymentMngtDao;
 import org.openbravo.advpaymentmngt.process.FIN_AddPayment;
 import org.openbravo.base.model.Entity;
@@ -387,12 +387,12 @@
   private static Sequence lockSequence(Sequence seq) {
     StringBuilder where = new StringBuilder("select s from ADSequence s where id = :id");
     final Session session = OBDal.getInstance().getSession();
-    final Query query = session.createQuery(where.toString());
+    final Query<Sequence> query = session.createQuery(where.toString(), Sequence.class);
     query.setParameter("id", seq.getId());
     query.setMaxResults(1);
     query.setLockOptions(LockOptions.UPGRADE);
     OBDal.getInstance().getSession().evict(seq);
-    return (Sequence) query.uniqueResult();
+    return query.uniqueResult();
   }
 
   /**
@@ -1278,15 +1278,10 @@
     hql.append(" and to_date('").append(dateAcct).append("') >= p.startingDate ");
     hql.append(" and to_date('").append(dateAcct).append("') < p.endingDate + 1 ");
 
-    final Query qry = session.createQuery(hql.toString());
+    final Query<String> qry = session.createQuery(hql.toString(), String.class);
 
-    String period = (String) (qry.list().get(0));
-
-    if (period == null) {
-      return false;
-    } else {
-      return true;
-    }
+    String period = qry.list().get(0);
+    return period != null;
   }
 
   public static boolean periodControlOpened(String tableName, String recordId, String idColumnName,
@@ -1391,7 +1386,6 @@
   /**
    * Returns Payment Details from a Payment ordered by Invoice and Order
    */
-  @SuppressWarnings("unchecked")
   public static List<String> getOrderedPaymentDetailList(String paymentId) {
 
     List<String> pdList = null;
@@ -1411,7 +1405,8 @@
       whereClause.append(", coalesce(psd."
           + FIN_PaymentScheduleDetail.PROPERTY_ORDERPAYMENTSCHEDULE + ",'0')");
 
-      Query query = OBDal.getInstance().getSession().createQuery(whereClause.toString());
+      Query<String> query = OBDal.getInstance().getSession()
+          .createQuery(whereClause.toString(), String.class);
       query.setParameter("paymentId", paymentId);
       pdList = query.list();
 
@@ -1433,9 +1428,9 @@
     hql.append(" from FIN_Payment p ");
     hql.append(" where p.reversedPayment = '").append(payment.getId()).append("' ");
 
-    final Query qry = session.createQuery(hql.toString());
+    final Query<Long> qry = session.createQuery(hql.toString(), Long.class);
 
-    return ((Long) qry.list().get(0) > Long.parseLong("0"));
+    return qry.list().get(0) > Long.parseLong("0");
   }
 
   /**
--- a/modules/org.openbravo.client.application/src-test/org/openbravo/client/application/test/ADCSInitialization.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/modules/org.openbravo.client.application/src-test/org/openbravo/client/application/test/ADCSInitialization.java	Tue Jul 24 10:44:21 2018 +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 Openbravo SLU 
+ * All portions are Copyright (C) 2017-2018 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -32,7 +32,7 @@
 
 import javax.inject.Inject;
 
-import org.hibernate.Query;
+import org.hibernate.query.Query;
 import org.junit.Test;
 import org.openbravo.base.exception.OBException;
 import org.openbravo.base.weld.test.WeldBaseTest;
@@ -134,16 +134,15 @@
       setSystemAdministratorContext();
     }
 
-    @SuppressWarnings("unchecked")
     private void eagerADCSInitialization() throws Exception {
       log.info("Starting eager initialization");
 
-      Query queryTabs = OBDal
+      Query<String> queryTabs = OBDal
           .getInstance()
           .getSession()
           .createQuery(
               "select t.id from ADTab t where t.active=true order by t.window.id, t.id "
-                  + (threadNum % 2 == 0 ? "asc" : "desc"));
+                  + (threadNum % 2 == 0 ? "asc" : "desc"), String.class);
 
       List<String> tabs = queryTabs.list();
       long t = System.currentTimeMillis();
@@ -157,11 +156,12 @@
       }
       log.info("Intialized all tabs in {} ms", System.currentTimeMillis() - t);
 
-      Query queryCombo = OBDal
+      Query<String> queryCombo = OBDal
           .getInstance()
           .getSession()
           .createQuery(
-              "select f.id from ADField f where f.active=true and f.column.reference.id in ('18','17','19')");
+              "select f.id from ADField f where f.active=true and f.column.reference.id in ('18','17','19')",
+              String.class);
 
       List<String> combos = queryCombo.list();
       long t1 = System.currentTimeMillis();
--- a/modules/org.openbravo.client.application/src/org/openbravo/client/application/ADAlertDatasourceService.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/modules/org.openbravo.client.application/src/org/openbravo/client/application/ADAlertDatasourceService.java	Tue Jul 24 10:44:21 2018 +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-2017 Openbravo SLU
+ * All portions are Copyright (C) 2015-2018 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -29,8 +29,8 @@
 import javax.servlet.ServletException;
 
 import org.apache.commons.lang.StringUtils;
-import org.hibernate.SQLQuery;
 import org.hibernate.exception.SQLGrammarException;
+import org.hibernate.query.NativeQuery;
 import org.openbravo.base.exception.OBException;
 import org.openbravo.base.model.Entity;
 import org.openbravo.base.model.ModelProvider;
@@ -106,7 +106,8 @@
         + "  AND ad_org_id " + OBDal.getInstance().getReadableOrganizationsInClause()
         + "  AND isactive='Y'";
 
-    final SQLQuery alertRules = OBDal.getInstance().getSession().createSQLQuery(sql);
+    @SuppressWarnings("rawtypes")
+    final NativeQuery alertRules = OBDal.getInstance().getSession().createNativeQuery(sql);
     alertRules.setParameter("userId", OBContext.getOBContext().getUser().getId());
     alertRules.setParameter("roleId", OBContext.getOBContext().getRole().getId());
     return getAlertIdsFromAlertRules(getAlertRulesGroupedByFilterClause(alertRules), alertStatus);
@@ -116,7 +117,8 @@
    * The method groups the AlertRule IDS by taking into account when they have the same filter
    * clause.
    */
-  private Map<String, List<String>> getAlertRulesGroupedByFilterClause(SQLQuery alertRules) {
+  @SuppressWarnings("rawtypes")
+  private Map<String, List<String>> getAlertRulesGroupedByFilterClause(NativeQuery alertRules) {
     Map<String, List<String>> alertRulesIdGroupByFilterClauses = new HashMap<>();
     try {
       for (Object resultObject : alertRules.list()) {
@@ -154,7 +156,8 @@
           + " AND ad_org_id " + OBDal.getInstance().getReadableOrganizationsInClause()
           + " AND ad_alertrule_id IN (" + commaSeparated(alertRuleList.getValue()) + ")"
           + filterClause + " AND coalesce(to_char(status), 'NEW') = :status";
-      final SQLQuery sqlQuery = OBDal.getInstance().getSession().createSQLQuery(sql);
+      @SuppressWarnings("rawtypes")
+      final NativeQuery sqlQuery = OBDal.getInstance().getSession().createNativeQuery(sql);
       sqlQuery.setParameter("status", alertStatus);
       try {
         @SuppressWarnings("unchecked")
--- a/modules/org.openbravo.client.application/src/org/openbravo/client/application/AlertActionHandler.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/modules/org.openbravo.client.application/src/org/openbravo/client/application/AlertActionHandler.java	Tue Jul 24 10:44:21 2018 +0200
@@ -29,7 +29,7 @@
 
 import org.apache.log4j.Logger;
 import org.codehaus.jettison.json.JSONObject;
-import org.hibernate.Query;
+import org.hibernate.query.Query;
 import org.openbravo.base.secureApp.VariablesSecureApp;
 import org.openbravo.client.kernel.BaseActionHandler;
 import org.openbravo.client.kernel.RequestContext;
@@ -86,7 +86,7 @@
         // select the alert rules
         final String hql = "select distinct(e.alertRule) from  "
             + AlertRecipient.ENTITY_NAME
-            + " e where e.alertRule.active = true and (e.userContact.id= :userId "
+            + " e where e.alertRule.active = true and (e.userContact.id = :userId "
             + " or (e.userContact.id = null and e.role.id = :roleId))"
 
             // select only those rules that are client/org visible from current role
@@ -94,12 +94,12 @@
             + " and e.alertRule.organization.id "
             + OBDal.getInstance().getReadableOrganizationsInClause();
 
-        final Query qry = OBDal.getInstance().getSession().createQuery(hql);
+        final Query<AlertRule> qry = OBDal.getInstance().getSession()
+            .createQuery(hql, AlertRule.class);
         qry.setParameter("userId", OBContext.getOBContext().getUser().getId());
         qry.setParameter("roleId", OBContext.getOBContext().getRole().getId());
 
-        for (Object o : qry.list()) {
-          final AlertRule alertRule = (AlertRule) o;
+        for (AlertRule alertRule : qry.list()) {
           final String whereClause = new UsedByLink().getWhereClause(vars, "",
               alertRule.getFilterClause() == null ? "" : alertRule.getFilterClause());
           final String sql = "select count(*) from AD_ALERT where COALESCE(to_char(STATUS), 'NEW')='NEW'"
--- a/modules/org.openbravo.client.application/src/org/openbravo/client/application/GlobalMenu.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/modules/org.openbravo.client.application/src/org/openbravo/client/application/GlobalMenu.java	Tue Jul 24 10:44:21 2018 +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-2017 Openbravo SLU
+ * All portions are Copyright (C) 2013-2018 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -28,8 +28,8 @@
 
 import javax.enterprise.context.ApplicationScoped;
 
-import org.hibernate.Query;
 import org.hibernate.criterion.Restrictions;
+import org.hibernate.query.Query;
 import org.openbravo.client.application.MenuManager.MenuEntryType;
 import org.openbravo.client.application.MenuManager.MenuOption;
 import org.openbravo.dal.service.OBCriteria;
@@ -119,8 +119,7 @@
     // Cache in DAL session all menu entries in a single query, so no need to query one by one
     // afterwards
     final String menuHql = "select m from ADMenu m left join fetch m.aDMenuTrlList where m.module.enabled=true";
-    final Query menuQry = OBDal.getInstance().getSession().createQuery(menuHql);
-    @SuppressWarnings("unchecked")
+    final Query<Menu> menuQry = OBDal.getInstance().getSession().createQuery(menuHql, Menu.class);
     List<Menu> menus = menuQry.list();
 
     List<TreeNode> nodes = treeNodes.list();
--- a/modules/org.openbravo.client.application/src/org/openbravo/client/application/MenuManager.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/modules/org.openbravo.client.application/src/org/openbravo/client/application/MenuManager.java	Tue Jul 24 10:44:21 2018 +0200
@@ -29,7 +29,7 @@
 import javax.inject.Inject;
 
 import org.hibernate.Hibernate;
-import org.hibernate.Query;
+import org.hibernate.query.Query;
 import org.openbravo.base.session.SessionFactoryController;
 import org.openbravo.dal.core.OBContext;
 import org.openbravo.dal.service.OBDal;
@@ -114,17 +114,17 @@
     return cachedMenu;
   }
 
-  @SuppressWarnings("unchecked")
   private void linkForms() {
     final String formsHql = "select fa.specialForm.id " + //
         " from ADFormAccess fa " + //
         "where fa.role.id=:roleId" + //
         "  and fa.active = true";
 
-    final Query formsQry = OBDal.getInstance().getSession().createQuery(formsHql);
+    final Query<String> formsQry = OBDal.getInstance().getSession()
+        .createQuery(formsHql, String.class);
     formsQry.setParameter("roleId", OBContext.getOBContext().getRole().getId());
 
-    for (String formId : (List<String>) formsQry.list()) {
+    for (String formId : formsQry.list()) {
       MenuOption option = getMenuOptionByType(MenuEntryType.Form, formId);
       if (option != null) {
         // allow access if not running in a webcontainer as then the config file can not be checked
@@ -135,17 +135,17 @@
     }
   }
 
-  @SuppressWarnings("unchecked")
   private void linkProcesses() {
     final String allowedProcessHql = "select pa.process.id " + //
         " from ADProcessAccess pa " + //
         "where pa.role = :role" + //
         "  and pa.active = true";
 
-    final Query allowedProcessQry = OBDal.getInstance().getSession().createQuery(allowedProcessHql);
+    final Query<String> allowedProcessQry = OBDal.getInstance().getSession()
+        .createQuery(allowedProcessHql, String.class);
     allowedProcessQry.setParameter("role", OBContext.getOBContext().getRole());
 
-    for (String processId : (List<String>) allowedProcessQry.list()) {
+    for (String processId : allowedProcessQry.list()) {
       MenuOption option = getMenuOptionByType(MenuEntryType.Process, processId);
       if (option != null) {
         // allow access if not running in a webcontainer as then the config file can not be checked
@@ -156,16 +156,16 @@
     }
   }
 
-  @SuppressWarnings("unchecked")
   private void linkProcessDefinition() {
     final String processHql = "select pa.obuiappProcess.id " + //
         " from OBUIAPP_Process_Access pa " + //
         "where pa.role = :role" + //
         "  and pa.active = true ";
-    final Query processQry = OBDal.getInstance().getSession().createQuery(processHql);
+    final Query<String> processQry = OBDal.getInstance().getSession()
+        .createQuery(processHql, String.class);
     processQry.setParameter("role", OBContext.getOBContext().getRole());
 
-    for (String processId : (List<String>) processQry.list()) {
+    for (String processId : processQry.list()) {
       MenuOption option = getMenuOptionByType(MenuEntryType.ProcessDefinition, processId);
       if (option != null) {
         option.setAccessGranted(true);
@@ -173,16 +173,16 @@
     }
   }
 
-  @SuppressWarnings("unchecked")
   private void linkViewDefinition() {
     final String processHql = "select va.viewImplementation.id " + //
         " from obuiapp_ViewRoleAccess va " + //
         "where va.role = :role" + //
         "  and va.active = true ";
-    final Query processQry = OBDal.getInstance().getSession().createQuery(processHql);
+    final Query<String> processQry = OBDal.getInstance().getSession()
+        .createQuery(processHql, String.class);
     processQry.setParameter("role", OBContext.getOBContext().getRole());
 
-    for (String processId : (List<String>) processQry.list()) {
+    for (String processId : processQry.list()) {
       MenuOption option = getMenuOptionByType(MenuEntryType.View, processId);
       if (option != null) {
         option.setAccessGranted(true);
@@ -199,11 +199,11 @@
         " and wa.active = true " + //
         " and (ta.active = true or ta.active is null) " + //
         " order by wa.id, t.sequenceNumber DESC ";
-    final Query windowsQry = OBDal.getInstance().getSession().createQuery(windowsHql);
+    final Query<Object[]> windowsQry = OBDal.getInstance().getSession()
+        .createQuery(windowsHql, Object[].class);
     windowsQry.setParameter("role", OBContext.getOBContext().getRole());
 
-    for (Object obj : windowsQry.list()) {
-      final Object[] row = (Object[]) obj;
+    for (Object[] row : windowsQry.list()) {
       final String windowId = (String) row[0];
       final String tabId = (String) row[1];
       final Boolean isEditableTab = (Boolean) row[2];
--- a/modules/org.openbravo.client.application/src/org/openbravo/client/application/ViewComponent.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/modules/org.openbravo.client.application/src/org/openbravo/client/application/ViewComponent.java	Tue Jul 24 10:44:21 2018 +0200
@@ -30,9 +30,9 @@
 
 import org.apache.commons.codec.digest.DigestUtils;
 import org.apache.commons.lang.StringUtils;
-import org.hibernate.Query;
 import org.hibernate.Session;
 import org.hibernate.criterion.Restrictions;
+import org.hibernate.query.Query;
 import org.openbravo.base.exception.OBException;
 import org.openbravo.base.util.OBClassLoader;
 import org.openbravo.base.weld.WeldUtils;
@@ -273,17 +273,17 @@
     }
 
     String tabHql = "select max(updated) from OBUIAPP_GC_Tab where tab.window.id = :windowId";
-    Query qryTabData = OBDal.getInstance().getSession().createQuery(tabHql);
+    Query<Date> qryTabData = OBDal.getInstance().getSession().createQuery(tabHql, Date.class);
     qryTabData.setParameter("windowId", window.getId());
-    Date tabUpdated = (Date) qryTabData.uniqueResult();
+    Date tabUpdated = qryTabData.uniqueResult();
     if (tabUpdated != null && lastModification.compareTo(tabUpdated) < 0) {
       lastModification = tabUpdated;
     }
 
     String fieldHql = "select max(updated) from OBUIAPP_GC_Field where obuiappGcTab.tab.window.id = :windowId";
-    Query qryFieldData = OBDal.getInstance().getSession().createQuery(fieldHql);
+    Query<Date> qryFieldData = OBDal.getInstance().getSession().createQuery(fieldHql, Date.class);
     qryFieldData.setParameter("windowId", window.getId());
-    Date fieldUpdated = (Date) qryFieldData.uniqueResult();
+    Date fieldUpdated = qryFieldData.uniqueResult();
     if (fieldUpdated != null && lastModification.compareTo(fieldUpdated) < 0) {
       lastModification = fieldUpdated;
     }
@@ -327,7 +327,6 @@
     return updated == null ? "" : updated.toString();
   }
 
-  @SuppressWarnings("unchecked")
   private List<String> getFieldsWithDisplayLogicAtServerLevel(String windowID) {
     StringBuilder where = new StringBuilder();
     where.append(" select displayLogicEvaluatedInTheServer");
@@ -338,7 +337,7 @@
     where.append("                  where t.window.id = :windowId)");
 
     Session session = OBDal.getInstance().getSession();
-    Query query = session.createQuery(where.toString());
+    Query<String> query = session.createQuery(where.toString(), String.class);
     query.setParameter("windowId", windowID);
 
     return query.list();
@@ -356,9 +355,9 @@
     where.append(" and coalesce(p.visibleAtOrganization, '0') = '0'");
 
     Session session = OBDal.getInstance().getSession();
-    Query query = session.createQuery(where.toString());
+    Query<Date> query = session.createQuery(where.toString(), Date.class);
     query.setParameterList("properties", preferenceSet);
-    Date lastUpdated = (Date) query.uniqueResult();
+    Date lastUpdated = query.uniqueResult();
 
     return lastUpdated;
   }
--- a/modules/org.openbravo.client.application/src/org/openbravo/client/application/attachment/AttachImplementationManager.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/modules/org.openbravo.client.application/src/org/openbravo/client/application/attachment/AttachImplementationManager.java	Tue Jul 24 10:44:21 2018 +0200
@@ -312,7 +312,8 @@
       final ZipOutputStream dest = new ZipOutputStream(os);
       HashMap<String, Integer> writtenFiles = new HashMap<String, Integer>();
       OBCriteria<Attachment> attachmentFiles = OBDao.getFilteredCriteria(Attachment.class,
-          Restrictions.eq("table.id", tableId), Restrictions.in("record", recordIds.split(",")));
+          Restrictions.eq("table.id", tableId),
+          Restrictions.in("record", (Object[]) recordIds.split(",")));
       attachmentFiles.setFilterOnReadableOrganization(false);
       for (Attachment attachmentFile : attachmentFiles.list()) {
         checkReadableAccess(attachmentFile);
--- a/modules/org.openbravo.client.application/src/org/openbravo/client/application/attachment/AttachmentAH.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/modules/org.openbravo.client.application/src/org/openbravo/client/application/attachment/AttachmentAH.java	Tue Jul 24 10:44:21 2018 +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-2016 Openbravo SLU
+ * All portions are Copyright (C) 2011-2018 Openbravo SLU
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -159,7 +159,8 @@
     String tableId = tab.getTable().getId();
 
     OBCriteria<Attachment> attachmentFiles = OBDao.getFilteredCriteria(Attachment.class,
-        Restrictions.eq("table.id", tableId), Restrictions.in("record", recordIds.split(",")));
+        Restrictions.eq("table.id", tableId),
+        Restrictions.in("record", (Object[]) recordIds.split(",")));
     // do not filter by the attachment's organization
     // if the user has access to the record where the file its attached, it has access to all
     // its attachments
--- a/modules/org.openbravo.client.application/src/org/openbravo/client/application/attachment/AttachmentUtils.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/modules/org.openbravo.client.application/src/org/openbravo/client/application/attachment/AttachmentUtils.java	Tue Jul 24 10:44:21 2018 +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-2017 Openbravo SLU
+ * All portions are Copyright (C) 2015-2018 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -28,8 +28,8 @@
 import org.apache.commons.lang.StringUtils;
 import org.codehaus.jettison.json.JSONException;
 import org.codehaus.jettison.json.JSONObject;
-import org.hibernate.Query;
 import org.hibernate.criterion.Restrictions;
+import org.hibernate.query.Query;
 import org.openbravo.base.exception.OBException;
 import org.openbravo.base.model.Entity;
 import org.openbravo.base.model.ModelProvider;
@@ -167,7 +167,7 @@
   public static List<JSONObject> getTabAttachmentsForRows(Tab tab, String[] recordIds) {
     String tableId = tab.getTable().getId();
     OBCriteria<Attachment> attachmentFiles = OBDao.getFilteredCriteria(Attachment.class,
-        Restrictions.eq("table.id", tableId), Restrictions.in("record", recordIds));
+        Restrictions.eq("table.id", tableId), Restrictions.in("record", (Object[]) recordIds));
     attachmentFiles.addOrderBy("creationDate", false);
     List<JSONObject> attachments = new ArrayList<>();
     // do not filter by the attachment's organization
@@ -200,10 +200,11 @@
     final StringBuilder hql = new StringBuilder();
     hql.append("SELECT MAX(pv.updated) FROM OBUIAPP_ParameterValue pv");
     hql.append(" WHERE pv.file.id =:fileId");
-    final Query query = OBDal.getInstance().getSession().createQuery(hql.toString());
+    final Query<Date> query = OBDal.getInstance().getSession()
+        .createQuery(hql.toString(), Date.class);
     query.setParameter("fileId", attachment.getId());
     query.setMaxResults(1);
-    Date metadataLastUpdate = (Date) query.uniqueResult();
+    Date metadataLastUpdate = query.uniqueResult();
     if (metadataLastUpdate == null || attachment.getUpdated().after(metadataLastUpdate)) {
       return attachment.getUpdated();
     }
@@ -229,8 +230,8 @@
     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 query = OBDal.getInstance().getSession().createQuery(hql);
-    query.setString("recordId", recordId);
+    final Query<Object> query = OBDal.getInstance().getSession().createQuery(hql, Object.class);
+    query.setParameter("recordId", recordId);
     try {
       return query.uniqueResult();
     } catch (Exception e) {
--- a/modules/org.openbravo.client.application/src/org/openbravo/client/application/businesslogic/CloneOrderActionHandler.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/modules/org.openbravo.client.application/src/org/openbravo/client/application/businesslogic/CloneOrderActionHandler.java	Tue Jul 24 10:44:21 2018 +0200
@@ -27,7 +27,7 @@
 import java.util.Map;
 
 import org.codehaus.jettison.json.JSONObject;
-import org.hibernate.Query;
+import org.hibernate.query.Query;
 import org.openbravo.base.exception.OBException;
 import org.openbravo.base.weld.WeldUtils;
 import org.openbravo.client.kernel.BaseActionHandler;
@@ -242,11 +242,12 @@
   public static BigDecimal getLineNetAmt(final String strOrderId) {
     BigDecimal bdLineNetAmt = new BigDecimal("0");
     final String readLineNetAmtHql = " select (coalesce(ol.lineNetAmount,0) + coalesce(ol.freightAmount,0) + coalesce(ol.chargeAmount,0)) as LineNetAmt from OrderLine ol where ol.salesOrder.id=:orderId";
-    final Query readLineNetAmtQry = OBDal.getInstance().getSession().createQuery(readLineNetAmtHql);
+    final Query<BigDecimal> readLineNetAmtQry = OBDal.getInstance().getSession()
+        .createQuery(readLineNetAmtHql, BigDecimal.class);
     readLineNetAmtQry.setParameter("orderId", strOrderId);
 
-    for (int i = 0; i < readLineNetAmtQry.list().size(); i++) {
-      bdLineNetAmt = bdLineNetAmt.add(((BigDecimal) readLineNetAmtQry.list().get(i)));
+    for (BigDecimal amount : readLineNetAmtQry.list()) {
+      bdLineNetAmt = bdLineNetAmt.add(amount);
     }
 
     return bdLineNetAmt;
--- a/modules/org.openbravo.client.application/src/org/openbravo/client/application/event/DataPoolSelectionEventHandler.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/modules/org.openbravo.client.application/src/org/openbravo/client/application/event/DataPoolSelectionEventHandler.java	Tue Jul 24 10:44:21 2018 +0200
@@ -22,6 +22,7 @@
 
 import org.apache.commons.lang.StringUtils;
 import org.apache.log4j.Logger;
+import org.hibernate.resource.transaction.spi.TransactionStatus;
 import org.openbravo.base.model.Entity;
 import org.openbravo.base.model.ModelProvider;
 import org.openbravo.client.application.DataPoolSelection;
@@ -78,7 +79,8 @@
   public void onTransactionCompleted(@Observes TransactionCompletedEvent event) {
     String strValueId = dataPoolSelectionValueUpdated.get();
     dataPoolSelectionValueUpdated.set(null);
-    if (StringUtils.isBlank(strValueId) || event.getTransaction().wasRolledBack()) {
+    if (StringUtils.isBlank(strValueId)
+        || event.getTransaction().getStatus() == TransactionStatus.ROLLED_BACK) {
       return;
     }
 
--- a/modules/org.openbravo.client.application/src/org/openbravo/client/application/example/GridExampleActionHandler.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/modules/org.openbravo.client.application/src/org/openbravo/client/application/example/GridExampleActionHandler.java	Tue Jul 24 10:44:21 2018 +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-2011 Openbravo SLU 
+ * All portions are Copyright (C) 2009-2018 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -26,7 +26,7 @@
 
 import org.codehaus.jettison.json.JSONArray;
 import org.codehaus.jettison.json.JSONObject;
-import org.hibernate.Query;
+import org.hibernate.query.Query;
 import org.openbravo.base.exception.OBException;
 import org.openbravo.client.kernel.BaseActionHandler;
 import org.openbravo.dal.core.OBContext;
@@ -89,11 +89,10 @@
     try {
       final String hql = "select module.id, module.name, count(window) from ADModule module, ADWindow window "
           + " where window.module=module group by module.id, module.name";
-      Query qry = OBDal.getInstance().getSession().createQuery(hql);
+      Query<Object[]> qry = OBDal.getInstance().getSession().createQuery(hql, Object[].class);
 
       final List<JSONObject> dataList = new ArrayList<JSONObject>();
-      for (Object o : qry.list()) {
-        final Object[] os = (Object[]) o;
+      for (Object[] os : qry.list()) {
         final JSONObject data = new JSONObject();
         data.put(ID, os[0]);
         data.put(NAME, os[1]);
--- a/modules/org.openbravo.client.application/src/org/openbravo/client/application/navigationbarcomponents/RoleInfo.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/modules/org.openbravo.client.application/src/org/openbravo/client/application/navigationbarcomponents/RoleInfo.java	Tue Jul 24 10:44:21 2018 +0200
@@ -25,7 +25,7 @@
 import java.util.Map;
 import java.util.Set;
 
-import org.hibernate.Query;
+import org.hibernate.query.Query;
 import org.openbravo.dal.core.OBContext;
 import org.openbravo.dal.security.OrganizationStructureProvider;
 import org.openbravo.dal.service.OBDal;
@@ -87,10 +87,10 @@
     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 ");
-    Query roleOrgs = OBDal.getInstance().getSession().createQuery(hql.toString());
-    roleOrgs.setString("roleId", roleId);
-    for (Object entry : roleOrgs.list()) {
-      final Object[] orgInfo = (Object[]) entry;
+    Query<Object[]> roleOrgs = OBDal.getInstance().getSession()
+        .createQuery(hql.toString(), Object[].class);
+    roleOrgs.setParameter("roleId", roleId);
+    for (Object[] orgInfo : roleOrgs.list()) {
       roleOrganizations.put((String) orgInfo[0], (String) orgInfo[1]);
     }
     return roleOrganizations;
@@ -113,11 +113,12 @@
     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 ");
-    Query orgWarehouses = OBDal.getInstance().getSession().createQuery(hql.toString());
+    Query<Object[]> orgWarehouses = OBDal.getInstance().getSession()
+        .createQuery(hql.toString(), Object[].class);
     orgWarehouses.setParameterList("orgList", getOrganizations().keySet());
-    orgWarehouses.setString("clientId", clientId);
-    for (Object entry : orgWarehouses.list()) {
-      RoleWarehouseInfo warehouseInfo = new RoleWarehouseInfo((Object[]) entry);
+    orgWarehouses.setParameter("clientId", clientId);
+    for (Object[] entry : orgWarehouses.list()) {
+      RoleWarehouseInfo warehouseInfo = new RoleWarehouseInfo(entry);
       for (Map.Entry<String, List<RoleWarehouseInfo>> ow : organizationWarehouses.entrySet()) {
         Set<String> naturalTree = getOrganizationStructureProvider().getNaturalTree(ow.getKey());
         if (naturalTree.contains(warehouseInfo.getWarehouseOrganizationId())) {
--- a/modules/org.openbravo.client.application/src/org/openbravo/client/application/navigationbarcomponents/UserInfoComponent.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/modules/org.openbravo.client.application/src/org/openbravo/client/application/navigationbarcomponents/UserInfoComponent.java	Tue Jul 24 10:44:21 2018 +0200
@@ -23,7 +23,7 @@
 
 import javax.servlet.http.HttpSession;
 
-import org.hibernate.Query;
+import org.hibernate.query.Query;
 import org.openbravo.client.kernel.KernelConstants;
 import org.openbravo.client.kernel.KernelServlet;
 import org.openbravo.client.kernel.SessionDynamicTemplateComponent;
@@ -108,10 +108,11 @@
     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 ");
-    Query rolesQry = OBDal.getInstance().getSession().createQuery(hql.toString());
-    rolesQry.setString("userId", OBContext.getOBContext().getUser().getId());
-    for (Object entry : rolesQry.list()) {
-      userRoles.add(new RoleInfo((Object[]) entry));
+    Query<Object[]> rolesQry = OBDal.getInstance().getSession()
+        .createQuery(hql.toString(), Object[].class);
+    rolesQry.setParameter("userId", OBContext.getOBContext().getUser().getId());
+    for (Object[] entry : rolesQry.list()) {
+      userRoles.add(new RoleInfo(entry));
     }
     return userRoles;
   }
--- a/modules/org.openbravo.client.application/src/org/openbravo/client/application/window/ApplicationDictionaryCachedStructures.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/modules/org.openbravo.client.application/src/org/openbravo/client/application/window/ApplicationDictionaryCachedStructures.java	Tue Jul 24 10:44:21 2018 +0200
@@ -29,7 +29,7 @@
 import javax.enterprise.context.ApplicationScoped;
 
 import org.hibernate.Hibernate;
-import org.hibernate.Query;
+import org.hibernate.query.Query;
 import org.openbravo.base.exception.OBException;
 import org.openbravo.client.application.Parameter;
 import org.openbravo.dal.service.OBDal;
@@ -107,10 +107,10 @@
     log.info("ADCS initialized, use cache: {}", useCache);
   }
 
-  @SuppressWarnings("unchecked")
   private Set<String> getModulesInDevelopment() {
     final String query = "select m.id from ADModule m where m.inDevelopment=true";
-    final Query indevelMods = OBDal.getInstance().getSession().createQuery(query);
+    final Query<String> indevelMods = OBDal.getInstance().getSession()
+        .createQuery(query, String.class);
     return new HashSet<>(indevelMods.list());
   }
 
--- a/modules/org.openbravo.client.myob/src/org/openbravo/client/myob/MyOBUtils.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/modules/org.openbravo.client.myob/src/org/openbravo/client/myob/MyOBUtils.java	Tue Jul 24 10:44:21 2018 +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-2017 Openbravo SLU
+ * All portions are Copyright (C) 2010-2018 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -29,8 +29,8 @@
 import org.codehaus.jettison.json.JSONArray;
 import org.codehaus.jettison.json.JSONException;
 import org.codehaus.jettison.json.JSONObject;
-import org.hibernate.Query;
 import org.hibernate.criterion.Restrictions;
+import org.hibernate.query.Query;
 import org.openbravo.base.exception.OBException;
 import org.openbravo.base.util.OBClassLoader;
 import org.openbravo.base.weld.WeldUtils;
@@ -213,7 +213,7 @@
     OBCriteria<WidgetInstance> criteria = getWidgetInstanceCriteria(priority, client, null, role);
     criteria.setFilterOnReadableOrganization(false);
     criteria.add(Restrictions.in(WidgetInstance.PROPERTY_ORGANIZATION + "."
-        + Organization.PROPERTY_ID, orgIds));
+        + Organization.PROPERTY_ID, (Object[]) orgIds));
     return criteria;
   }
 
@@ -297,7 +297,6 @@
     return anonymousWidgetClasses;
   }
 
-  @SuppressWarnings("unchecked")
   List<String> getAnonymousAccessibleWidgetClassesFromDatabase() {
     final StringBuilder hql = new StringBuilder();
     hql.append("SELECT widgetClass.id ");
@@ -305,7 +304,8 @@
     hql.append("WHERE widgetClass.allowAnonymousAccess IS true ");
     hql.append("AND widgetClass.superclass IS false ");
     hql.append("AND widgetClass.availableInWorkspace IS true");
-    Query query = OBDal.getInstance().getSession().createQuery(hql.toString());
+    Query<String> query = OBDal.getInstance().getSession()
+        .createQuery(hql.toString(), String.class);
     return query.list();
   }
 }
--- a/modules/org.openbravo.client.myob/src/org/openbravo/client/myob/MyOpenbravoComponent.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/modules/org.openbravo.client.myob/src/org/openbravo/client/myob/MyOpenbravoComponent.java	Tue Jul 24 10:44:21 2018 +0200
@@ -30,8 +30,8 @@
 import org.apache.log4j.Logger;
 import org.codehaus.jettison.json.JSONException;
 import org.codehaus.jettison.json.JSONObject;
-import org.hibernate.Query;
 import org.hibernate.criterion.Restrictions;
+import org.hibernate.query.Query;
 import org.openbravo.client.application.ApplicationUtils;
 import org.openbravo.client.kernel.SessionDynamicTemplateComponent;
 import org.openbravo.dal.core.DalUtil;
@@ -135,7 +135,6 @@
     }
   }
 
-  @SuppressWarnings("unchecked")
   private List<String> getAccessibleWidgetClassIds(String roleId, String additionalWhereClause) {
     final StringBuilder hql = new StringBuilder();
     hql.append("SELECT widgetClassAccess.widgetClass.id ");
@@ -145,11 +144,12 @@
     if (!StringUtils.isEmpty(additionalWhereClause)) {
       hql.append(additionalWhereClause);
     }
-    Query query = OBDal.getInstance().getSession().createQuery(hql.toString());
+    Query<String> query = OBDal.getInstance().getSession()
+        .createQuery(hql.toString(), String.class);
     if (StringUtils.isEmpty(roleId)) {
-      query.setString("roleId", OBContext.getOBContext().getRole().getId());
+      query.setParameter("roleId", OBContext.getOBContext().getRole().getId());
     } else {
-      query.setString("roleId", roleId);
+      query.setParameter("roleId", roleId);
     }
     List<String> widgetClassIds = query.list();
     List<String> anonymousWidgetClasses;
--- a/modules/org.openbravo.client.myob/src/org/openbravo/client/myob/WidgetProvider.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/modules/org.openbravo.client.myob/src/org/openbravo/client/myob/WidgetProvider.java	Tue Jul 24 10:44:21 2018 +0200
@@ -32,7 +32,7 @@
 import org.apache.log4j.Logger;
 import org.codehaus.jettison.json.JSONException;
 import org.codehaus.jettison.json.JSONObject;
-import org.hibernate.Query;
+import org.hibernate.query.Query;
 import org.openbravo.base.exception.OBException;
 import org.openbravo.base.model.Entity;
 import org.openbravo.base.model.ModelProvider;
@@ -410,17 +410,17 @@
   public static Map<String, String> createValueMap(Set<String> allowedValues, String referenceId) {
     final String userLanguageId = OBContext.getOBContext().getLanguage().getId();
 
-    final Map<String, String> translatedValues = new LinkedHashMap<String, String>();
+    final Map<String, String> translatedValues = new LinkedHashMap<>();
 
     for (String allowedValue : allowedValues) {
       translatedValues.put(allowedValue, allowedValue);
     }
 
     final String readReferenceHql = "select searchKey, name from ADList where reference.id=:referenceId";
-    final Query readReferenceQry = OBDal.getInstance().getSession().createQuery(readReferenceHql);
+    final Query<Object[]> readReferenceQry = OBDal.getInstance().getSession()
+        .createQuery(readReferenceHql, Object[].class);
     readReferenceQry.setParameter("referenceId", referenceId);
-    for (Object o : readReferenceQry.list()) {
-      final Object[] row = (Object[]) o;
+    for (Object[] row : readReferenceQry.list()) {
       final String value = (String) row[0];
       final String name = (String) row[1];
       if (allowedValues.contains(value)) {
@@ -432,11 +432,10 @@
     final String hql = "select al.searchKey, trl.name from ADList al, ADListTrl trl where "
         + " al.reference.id=:referenceId and trl.listReference=al and trl.language.id=:languageId"
         + " and al.active=true and trl.active=true";
-    final Query qry = OBDal.getInstance().getSession().createQuery(hql);
+    final Query<Object[]> qry = OBDal.getInstance().getSession().createQuery(hql, Object[].class);
     qry.setParameter("referenceId", referenceId);
     qry.setParameter("languageId", userLanguageId);
-    for (Object o : qry.list()) {
-      final Object[] row = (Object[]) o;
+    for (Object[] row : qry.list()) {
       translatedValues.put((String) row[0], (String) row[1]);
     }
     return translatedValues;
--- a/modules/org.openbravo.client.querylist/src/org/openbravo/client/querylist/QueryListDataSource.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/modules/org.openbravo.client.querylist/src/org/openbravo/client/querylist/QueryListDataSource.java	Tue Jul 24 10:44:21 2018 +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-2016 Openbravo SLU
+ * All portions are Copyright (C) 2010-2018 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -34,13 +34,16 @@
 import java.util.Map;
 import java.util.Set;
 
+import javax.persistence.Tuple;
+import javax.persistence.TupleElement;
+
 import org.apache.commons.lang.StringUtils;
 import org.apache.log4j.Logger;
 import org.codehaus.jettison.json.JSONArray;
 import org.codehaus.jettison.json.JSONException;
 import org.codehaus.jettison.json.JSONObject;
-import org.hibernate.Query;
 import org.hibernate.criterion.Restrictions;
+import org.hibernate.query.Query;
 import org.openbravo.base.exception.OBException;
 import org.openbravo.base.exception.OBSecurityException;
 import org.openbravo.base.model.ModelProvider;
@@ -65,6 +68,8 @@
 import org.openbravo.dal.service.OBCriteria;
 import org.openbravo.dal.service.OBDal;
 import org.openbravo.erpCommon.utility.OBMessageUtils;
+import org.openbravo.model.ad.access.Role;
+import org.openbravo.model.ad.access.User;
 import org.openbravo.model.ad.access.WindowAccess;
 import org.openbravo.model.ad.datamodel.Column;
 import org.openbravo.model.ad.domain.Reference;
@@ -101,24 +106,22 @@
       if (wi == null) {
         accessibleWidgetInForm = isAccessibleWidgetInForm(widgetClass);
       }
+
+      User ctxUser = OBContext.getOBContext().getUser();
+      Role ctxRole = OBContext.getOBContext().getRole();
+
       if (!accessibleWidgetInForm
           && (wi == null || !wi.getWidgetClass().getId().equals(widgetClass.getId()))) {
         // weird stuff: widget class doesn't match widget instance's class, most probably URL is
         // not generated by UI, but user is typing it
-        log.error("User " + OBContext.getOBContext().getUser() + " with role "
-            + OBContext.getOBContext().getRole() + " is trying to access widget '"
+        log.error("User " + ctxUser + " with role " + ctxRole + " is trying to access widget '"
             + widgetClass.getWidgetTitle() + "' but widget instance doesn't match with class");
         throw new OBSecurityException(OBMessageUtils.getI18NMessage("OBCQL_NoAccessToWidget",
             new String[] { widgetClass.getWidgetTitle() }));
       }
 
-      if (!accessibleWidgetInForm
-          && (OBContext.getOBContext() != null
-              && ((wi.getVisibleAtUser() != null && !wi.getVisibleAtUser().getId()
-                  .equals(OBContext.getOBContext().getUser().getId()))) || (wi.getVisibleAtRole() != null && !wi
-              .getVisibleAtRole().getId().equals(OBContext.getOBContext().getRole().getId())))) {
-        log.error("User " + OBContext.getOBContext().getUser() + " with role "
-            + OBContext.getOBContext().getRole() + " is trying to access widget '"
+      if (!accessibleWidgetInForm && !isAccessibleWidget(wi, ctxUser.getId(), ctxRole.getId())) {
+        log.error("User " + ctxUser + " with role " + ctxRole + " is trying to access widget '"
             + widgetClass.getWidgetTitle() + "' which is not granted");
         throw new OBSecurityException(OBMessageUtils.getI18NMessage("OBCQL_NoAccessToWidget",
             new String[] { widgetClass.getWidgetTitle() }));
@@ -128,6 +131,14 @@
     }
   }
 
+  private boolean isAccessibleWidget(WidgetInstance wi, String userId, String roleId) {
+    boolean visibleAtUser = wi.getVisibleAtUser() != null ? wi.getVisibleAtUser().getId()
+        .equals(userId) : true;
+    boolean visibleAtRole = wi.getVisibleAtRole() != null ? wi.getVisibleAtRole().getId()
+        .equals(roleId) : true;
+    return visibleAtUser || visibleAtRole;
+  }
+
   /**
    * Returns the count of objects based on the passed parameters.
    * 
@@ -187,9 +198,9 @@
         HQL = updateSortByFields(HQL, parameters.get(JsonConstants.SORTBY_PARAMETER));
       }
 
-      Query widgetQuery = null;
+      Query<Tuple> widgetQuery = null;
       try {
-        widgetQuery = OBDal.getInstance().getSession().createQuery(HQL);
+        widgetQuery = OBDal.getInstance().getSession().createQuery(HQL, Tuple.class);
       } catch (Exception e) {
         if (fetchingSummaryFields) {
           log.error("Exception while fetching the summary columns of the widget "
@@ -203,10 +214,9 @@
         final List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
         return result;
       }
-      String[] queryAliases = widgetQuery.getReturnAliases();
 
       if (!isExport && "widget".equals(viewMode) && !showAll) {
-        int rowsNumber = Integer.valueOf((parameters.get("rowsNumber") != null && !parameters.get(
+        int rowsNumber = Integer.parseInt((parameters.get("rowsNumber") != null && !parameters.get(
             "rowsNumber").equals("null")) ? parameters.get("rowsNumber") : "10");
         widgetQuery.setMaxResults(rowsNumber);
       } else if (!isExport) {
@@ -218,12 +228,11 @@
         }
       }
 
-      String[] params = widgetQuery.getNamedParameters();
-      if (params.length > 0) {
+      Set<String> params = widgetQuery.getParameterMetadata().getNamedParameterNames();
+      if (!params.isEmpty()) {
         HashMap<String, Object> parameterValues = getParameterValues(parameters, widgetClass);
 
-        for (int i = 0; i < params.length; i++) {
-          String namedParam = params[i];
+        for (String namedParam : params) {
           boolean isParamSet = false;
           if (parameterValues.containsKey(namedParam)) {
             Object value = parameterValues.get(namedParam);
@@ -245,28 +254,20 @@
         }
       }
 
-      final List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
+      final List<Map<String, Object>> result = new ArrayList<>();
 
       if (fetchingSummaryFields) {
         // process the response for the summary row
-        Map<String, Object> summaryData = new LinkedHashMap<String, Object>();
+        Map<String, Object> summaryData = new LinkedHashMap<>();
         try {
           JSONObject summaryFieldsObject = new JSONObject(
               parameters.get(JsonConstants.SUMMARY_PARAMETER));
+          Tuple uniqueResult = widgetQuery.uniqueResult();
           Iterator<?> summaryFieldNameIterator = summaryFieldsObject.keys();
-          Object uniqueResult = widgetQuery.uniqueResult();
-          if (uniqueResult instanceof Object[]) {
-            // handles the case where the values of several summary fields are request
-            Object[] summaryValues = (Object[]) uniqueResult;
-            int i = 0;
-            while (summaryFieldNameIterator.hasNext()) {
-              String summaryFieldName = (String) summaryFieldNameIterator.next();
-              summaryData.put(summaryFieldName, summaryValues[i++]);
-            }
-          } else {
-            // handles the case where the value of just one summary field is request
-            String summaryFieldName = (String) summaryFieldsObject.names().get(0);
-            summaryData.put(summaryFieldName, uniqueResult);
+          int i = 0;
+          while (summaryFieldNameIterator.hasNext()) {
+            String summaryFieldName = (String) summaryFieldNameIterator.next();
+            summaryData.put(summaryFieldName, uniqueResult.get(i++));
           }
           summaryData.put("isGridSummary", true);
         } catch (Exception e) {
@@ -278,40 +279,33 @@
 
       } else {
         // process the response for the grid
-        for (Object objResult : widgetQuery.list()) {
-          final Map<String, Object> data = new LinkedHashMap<String, Object>();
-          Object[] resultList = new Object[1];
-          if (objResult instanceof Object[]) {
-            resultList = (Object[]) objResult;
-          } else {
-            resultList[0] = objResult;
-          }
+        for (Tuple tuple : widgetQuery.list()) {
+          final Map<String, Object> data = new LinkedHashMap<>();
 
           for (OBCQL_QueryColumn column : columns) {
             UIDefinition uiDefinition = UIDefinitionController.getInstance().getUIDefinition(
                 column.getReference());
             DomainType domainType = uiDefinition.getDomainType();
-            // TODO: throw an exception if the display expression doesn't match any returned alias.
-            for (int i = 0; i < queryAliases.length; i++) {
-              if (queryAliases[i].equals(column.getDisplayExpression())
-                  || (!isExport && queryAliases[i].equals(column.getLinkExpression()))) {
-                Object value = resultList[i];
-                if ((domainType instanceof DateDomainType || domainType instanceof DateDomainType)
-                    && value != null) {
+            for (TupleElement<?> tupleElement : tuple.getElements()) {
+              String alias = tupleElement.getAlias();
+              if (alias == null) {
+                continue;
+              } else if (alias.equals(column.getDisplayExpression())
+                  || (!isExport && alias.equals(column.getLinkExpression()))) {
+                Object value = tuple.get(tupleElement.getAlias());
+                if (domainType instanceof DateDomainType && value != null) {
                   value = xmlDateFormat.format(value);
                 } else if (value instanceof Timestamp && value != null) {
                   value = xmlDateTimeFormat.format(value);
                   value = JsonUtils.convertToCorrectXSDFormat((String) value);
                 }
 
-                if (domainType instanceof BooleanDomainType) {
-                  if (value instanceof String) {
-                    value = ((PrimitiveDomainType) domainType).createFromString((String) value);
-                  }
+                if (domainType instanceof BooleanDomainType && value instanceof String) {
+                  value = ((PrimitiveDomainType) domainType).createFromString((String) value);
                 }
 
                 if (!isExport) {
-                  data.put(queryAliases[i], value);
+                  data.put(tupleElement.getAlias(), value);
                 } else {
                   data.put(QueryListUtils.getColumnLabel(column), value);
                 }
@@ -340,7 +334,8 @@
    */
   private String updateSortByFields(String hql, String sortBy) {
     String[] fieldList = null;
-    String sortByClause = "", hqlString = hql;
+    String sortByClause = "";
+    String hqlString = hql;
     if (sortBy.contains(",")) {
       fieldList = sortBy.split(",");
     }
@@ -476,7 +471,7 @@
     OBCriteria<WidgetReference> widgetInFormCriteria = OBDal.getInstance().createCriteria(
         WidgetReference.class);
     widgetInFormCriteria.add(Restrictions.eq(WidgetReference.PROPERTY_WIDGETCLASS, widgetClass));
-    List<Window> windowList = new ArrayList<Window>();
+    List<Window> windowList = new ArrayList<>();
     List<WidgetReference> widgetInFormList = widgetInFormCriteria.list();
     for (WidgetReference widgetInForm : widgetInFormList) {
       List<Column> columnList = widgetInForm.getReference().getADColumnReferenceSearchKeyList();
@@ -523,11 +518,7 @@
     } else {
       DomainType domainType = ModelProvider.getInstance()
           .getReference(parameterToCheck.getReference().getId()).getDomainType();
-      if (domainType.getClass().equals(DateDomainType.class)) {
-        return true;
-      } else {
-        return false;
-      }
+      return domainType.getClass().equals(DateDomainType.class);
     }
   }
 
@@ -543,7 +534,7 @@
    */
   private HashMap<String, Object> getParameterValues(Map<String, String> parameters,
       WidgetClass widgetClass) {
-    HashMap<String, Object> parameterValues = new HashMap<String, Object>();
+    HashMap<String, Object> parameterValues = new HashMap<>();
 
     // get serializedValues from request (if present)
     String serializedParams = parameters.get("serializedParameters");
@@ -577,7 +568,7 @@
 
   private String parseOptionalFilters(String _HQL, String viewMode, Map<String, String> parameters,
       List<OBCQL_QueryColumn> columns, SimpleDateFormat xmlDateFormat) {
-    StringBuffer optionalFilter = new StringBuffer(" 1=1 ");
+    StringBuilder optionalFilter = new StringBuilder(" 1=1 ");
     String HQL = _HQL;
 
     // Parse for columns filtered by grid's filter row on maximized view. If we are not on maximized
@@ -649,7 +640,7 @@
   public List<DataSourceProperty> getDataSourceProperties(Map<String, Object> parameters) {
     // note datasource properties are not cached as the component is
     // re-used within one request thread
-    final List<DataSourceProperty> dsProperties = new ArrayList<DataSourceProperty>();
+    final List<DataSourceProperty> dsProperties = new ArrayList<>();
     OBContext.setAdminMode();
     try {
       WidgetClass widgetClass = (WidgetClass) parameters
@@ -692,7 +683,6 @@
                     .getReferenceSearchKey().getId()));
               }
             }
-          } else {
           }
           dsProperties.add(dsProperty);
         }
@@ -712,7 +702,7 @@
     private ArrayList<String> compareByArray;
 
     public DataComparator(String compareBy) {
-      this.compareByArray = new ArrayList<String>();
+      this.compareByArray = new ArrayList<>();
       if (compareBy.contains(JsonConstants.IN_PARAMETER_SEPARATOR)) {
         final String[] separatedValues = compareBy.split(JsonConstants.IN_PARAMETER_SEPARATOR);
         for (String separatedValue : separatedValues) {
--- a/modules/org.openbravo.financial.paymentreport/src/org/openbravo/financial/paymentreport/erpCommon/ad_reports/PaymentReportDao.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/modules/org.openbravo.financial.paymentreport/src/org/openbravo/financial/paymentreport/erpCommon/ad_reports/PaymentReportDao.java	Tue Jul 24 10:44:21 2018 +0200
@@ -37,12 +37,13 @@
 import org.apache.commons.lang.time.DateUtils;
 import org.apache.log4j.Logger;
 import org.hibernate.LockOptions;
-import org.hibernate.Query;
 import org.hibernate.ScrollMode;
 import org.hibernate.ScrollableResults;
 import org.hibernate.Session;
 import org.hibernate.criterion.Order;
 import org.hibernate.criterion.Restrictions;
+import org.hibernate.query.Query;
+import org.hibernate.sql.JoinType;
 import org.openbravo.advpaymentmngt.utility.FIN_Utility;
 import org.openbravo.base.exception.OBException;
 import org.openbravo.base.secureApp.VariablesSecureApp;
@@ -260,7 +261,7 @@
     Currency transCurrency;
     BigDecimal transAmount = null;
     ConversionRate convRate = null;
-    ArrayList<FieldProvider> totalData = new ArrayList<FieldProvider>();
+    ArrayList<FieldProvider> totalData = new ArrayList<>();
     int numberOfElements = 0;
     int lastElement = 0;
     ScrollableResults scroller = null;
@@ -591,18 +592,12 @@
       if (StringUtils.equals(strOutput, "HTML")) {
         int maxRecords = 1000;
         final Session sessionCount = OBDal.getReadOnlyInstance().getSession();
-        final Query queryCount = sessionCount
-            .createQuery("select count(*)" + hsqlScript.toString());
+        final Query<Long> queryCount = sessionCount.createQuery(
+            "select count(*)" + hsqlScript.toString(), Long.class);
         for (Entry<String, Object> entry : parameters.entrySet()) {
-          String paramName = entry.getKey();
-          Object param = entry.getValue();
-          if (param instanceof BaseOBObject) {
-            queryCount.setEntity(paramName, param);
-          } else {
-            queryCount.setParameter(paramName, param);
-          }
+          queryCount.setParameter(entry.getKey(), entry.getValue());
         }
-        final Long hqlRecordsCount = (Long) queryCount.list().get(0);
+        final Long hqlRecordsCount = queryCount.list().get(0);
         if ((int) (long) hqlRecordsCount > maxRecords) {
           String message = "FINPR_TooManyRecords";
           throw new OBException(message);
@@ -710,16 +705,10 @@
       hsqlScript.append(".");
       hsqlScript.append(FIN_PaymentSchedule.PROPERTY_ID);
       final Session session = OBDal.getReadOnlyInstance().getSession();
-      final Query query = session.createQuery(hsqlScript.toString());
+      final Query<Object[]> query = session.createQuery(hsqlScript.toString(), Object[].class);
 
       for (Entry<String, Object> entry : parameters.entrySet()) {
-        String paramName = entry.getKey();
-        Object param = entry.getValue();
-        if (param instanceof BaseOBObject) {
-          query.setEntity(paramName, param);
-        } else {
-          query.setParameter(paramName, param);
-        }
+        query.setParameter(entry.getKey(), entry.getValue());
       }
 
       scroller = query.scroll(ScrollMode.FORWARD_ONLY);
@@ -1693,13 +1682,13 @@
    * elsewise it returns false
    */
   private boolean isBeforeStatus(String firstValue, String secondValue) {
-    String[] strStatus = { firstValue, secondValue };
+    Object[] strStatus = { firstValue, secondValue };
     boolean isBefore = false;
 
     OBContext.setAdminMode(true);
     try {
       OBCriteria<List> obCriteria = OBDal.getReadOnlyInstance().createCriteria(List.class);
-      obCriteria.createAlias(List.PROPERTY_REFERENCE, "r", OBCriteria.LEFT_JOIN);
+      obCriteria.createAlias(List.PROPERTY_REFERENCE, "r", JoinType.LEFT_OUTER_JOIN);
       obCriteria.add(Restrictions.ilike("r."
           + org.openbravo.model.ad.domain.Reference.PROPERTY_NAME, "FIN_Payment status"));
       obCriteria.add(Restrictions.in(List.PROPERTY_SEARCHKEY, strStatus));
@@ -1746,19 +1735,19 @@
       OBCriteria<FIN_FinaccTransaction> obCriteriaTrans = OBDal.getReadOnlyInstance()
           .createCriteria(FIN_FinaccTransaction.class);
       obCriteriaTrans.createAlias(FIN_FinaccTransaction.PROPERTY_BUSINESSPARTNER, "bp",
-          OBCriteria.LEFT_JOIN);
+          JoinType.LEFT_OUTER_JOIN);
       obCriteriaTrans.createAlias("bp." + BusinessPartner.PROPERTY_BUSINESSPARTNERCATEGORY, "bpc",
-          OBCriteria.LEFT_JOIN);
-      obCriteriaTrans
-          .createAlias(FIN_FinaccTransaction.PROPERTY_PROJECT, "p", OBCriteria.LEFT_JOIN);
+          JoinType.LEFT_OUTER_JOIN);
+      obCriteriaTrans.createAlias(FIN_FinaccTransaction.PROPERTY_PROJECT, "p",
+          JoinType.LEFT_OUTER_JOIN);
       obCriteriaTrans.createAlias(FIN_FinaccTransaction.PROPERTY_CURRENCY, "c",
-          OBCriteria.LEFT_JOIN);
+          JoinType.LEFT_OUTER_JOIN);
       obCriteriaTrans.createAlias(FIN_FinaccTransaction.PROPERTY_ACCOUNT, "acc",
-          OBCriteria.LEFT_JOIN);
+          JoinType.LEFT_OUTER_JOIN);
       obCriteriaTrans.add(Restrictions.isNull(FIN_FinaccTransaction.PROPERTY_FINPAYMENT));
       obCriteriaTrans.add(Restrictions.eq(FIN_FinaccTransaction.PROPERTY_PROCESSED, true));
       obCriteriaTrans.add(Restrictions.in(FIN_FinaccTransaction.PROPERTY_ORGANIZATION,
-          organizations));
+          (Object[]) organizations));
 
       // Empty Business Partner included
       if (StringUtils.equals(strcNoBusinessPartner, "include")) {
@@ -1860,7 +1849,7 @@
         localStrfinPaymSt = localStrfinPaymSt.replace(")", "");
         localStrfinPaymSt = localStrfinPaymSt.replace("'", "");
         localStrfinPaymSt = localStrfinPaymSt.replace(" ", "");
-        String[] status = localStrfinPaymSt.split(",");
+        Object[] status = localStrfinPaymSt.split(",");
         obCriteriaTrans.add(Restrictions.in(FIN_FinaccTransaction.PROPERTY_STATUS, status));
       }
 
@@ -1872,10 +1861,10 @@
 
       // payment type
       if (StringUtils.equalsIgnoreCase(strPaymType, "FINPR_Receivables")) {
-        String[] status = { "PWNC", "RPPC" };
+        Object[] status = { "PWNC", "RPPC" };
         obCriteriaTrans.add(Restrictions.in(FIN_FinaccTransaction.PROPERTY_STATUS, status));
       } else if (StringUtils.equalsIgnoreCase(strPaymType, "FINPR_Payables")) {
-        String[] status = { "RDNC", "RPPC" };
+        Object[] status = { "RDNC", "RPPC" };
         obCriteriaTrans.add(Restrictions.in(FIN_FinaccTransaction.PROPERTY_STATUS, status));
       }
 
@@ -2162,9 +2151,9 @@
     try {
       OBContext.setAdminMode(true);
       final Session session = OBDal.getReadOnlyInstance().getSession();
-      final Query query = session.createQuery(sql.toString());
+      final Query<String> query = session.createQuery(sql.toString(), String.class);
       query.setParameter("paymentId", payment.getId());
-      for (final Object o : query.list()) {
+      for (final String o : query.list()) {
         result.add(OBDal.getReadOnlyInstance().get(Invoice.class, o));
       }
 
@@ -2186,10 +2175,9 @@
     try {
       OBContext.setAdminMode(true);
       final Session session = OBDal.getReadOnlyInstance().getSession();
-      final Query query = session.createQuery(sql.toString());
-      @SuppressWarnings("unchecked")
-      java.util.List<FIN_PaymentSchedule> psList = query.list();
-      return psList;
+      final Query<FIN_PaymentSchedule> query = session.createQuery(sql.toString(),
+          FIN_PaymentSchedule.class);
+      return query.list();
     } finally {
       OBContext.restorePreviousMode();
     }
@@ -2208,8 +2196,9 @@
     try {
       OBContext.setAdminMode(true);
       final Session session = OBDal.getReadOnlyInstance().getSession();
-      final Query query = session.createQuery(sql.toString());
-      return (FIN_PaymentSchedule) query.uniqueResult();
+      final Query<FIN_PaymentSchedule> query = session.createQuery(sql.toString(),
+          FIN_PaymentSchedule.class);
+      return query.uniqueResult();
     } finally {
       OBContext.restorePreviousMode();
     }
--- a/modules/org.openbravo.service.datasource/src/org/openbravo/service/datasource/ADTreeDatasourceService.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/modules/org.openbravo.service.datasource/src/org/openbravo/service/datasource/ADTreeDatasourceService.java	Tue Jul 24 10:44:21 2018 +0200
@@ -235,7 +235,7 @@
 
     boolean fetchRoot = ROOT_NODE_CLIENT.equals(parentId);
     int cont = 0;
-    ScrollableResults scrollNodes = obq.createQuery().scroll(ScrollMode.FORWARD_ONLY);
+    ScrollableResults scrollNodes = obq.createQuery(Object[].class).scroll(ScrollMode.FORWARD_ONLY);
     try {
       while (scrollNodes.next()) {
         Object[] node = scrollNodes.get();
--- a/modules/org.openbravo.service.datasource/src/org/openbravo/service/datasource/DataSourceProperty.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/modules/org.openbravo.service.datasource/src/org/openbravo/service/datasource/DataSourceProperty.java	Tue Jul 24 10:44:21 2018 +0200
@@ -25,7 +25,7 @@
 import java.util.List;
 import java.util.Set;
 
-import org.hibernate.Query;
+import org.hibernate.query.Query;
 import org.openbravo.base.exception.OBException;
 import org.openbravo.base.model.Entity;
 import org.openbravo.base.model.ModelProvider;
@@ -142,13 +142,12 @@
    *          List reference
    */
   public static Set<String> getAllowedValues(Reference reference) {
-    Set<String> allowedValues = new HashSet<String>();
+    Set<String> allowedValues = new HashSet<>();
 
     final String hql = "select al.searchKey from ADList al" + " where al.reference=:ref";
-    final Query qry = OBDal.getInstance().getSession().createQuery(hql);
+    final Query<String> qry = OBDal.getInstance().getSession().createQuery(hql, String.class);
     qry.setParameter("ref", reference);
-    for (Object o : qry.list()) {
-      final String value = (String) o;
+    for (String value : qry.list()) {
       allowedValues.add(value);
     }
     return allowedValues;
@@ -157,13 +156,13 @@
   public static List<RefListEntry> createValueMap(Set<String> allowedValues, String referenceId) {
     final String userLanguageId = OBContext.getOBContext().getLanguage().getId();
 
-    final List<RefListEntry> translatedValues = new ArrayList<RefListEntry>();
+    final List<RefListEntry> translatedValues = new ArrayList<>();
 
     final String readReferenceHql = "select searchKey, name, sequenceNumber from ADList rlist where reference.id=:referenceId and rlist.active=true";
-    final Query readReferenceQry = OBDal.getInstance().getSession().createQuery(readReferenceHql);
+    final Query<Object[]> readReferenceQry = OBDal.getInstance().getSession()
+        .createQuery(readReferenceHql, Object[].class);
     readReferenceQry.setParameter("referenceId", referenceId);
-    for (Object o : readReferenceQry.list()) {
-      final Object[] row = (Object[]) o;
+    for (Object[] row : readReferenceQry.list()) {
       final String value = (String) row[0];
       final String name = (String) row[1];
       final Long seqNo = (Long) row[2];
@@ -185,11 +184,10 @@
       final String hql = "select al.searchKey, trl.name from ADList al, ADListTrl trl where "
           + " al.reference.id=:referenceId and trl.listReference=al and trl.language.id=:languageId"
           + " and al.active=true and trl.active=true";
-      final Query qry = OBDal.getInstance().getSession().createQuery(hql);
+      final Query<Object[]> qry = OBDal.getInstance().getSession().createQuery(hql, Object[].class);
       qry.setParameter("referenceId", referenceId);
       qry.setParameter("languageId", userLanguageId);
-      for (Object o : qry.list()) {
-        final Object[] row = (Object[]) o;
+      for (Object[] row : qry.list()) {
         for (RefListEntry entry : translatedValues) {
           if (entry.getValue().equalsIgnoreCase((String) row[0])) {
             entry.setLabel((String) row[1]);
--- a/modules/org.openbravo.service.datasource/src/org/openbravo/service/datasource/DataSourceServlet.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/modules/org.openbravo.service.datasource/src/org/openbravo/service/datasource/DataSourceServlet.java	Tue Jul 24 10:44:21 2018 +0200
@@ -47,9 +47,9 @@
 import org.codehaus.jettison.json.JSONArray;
 import org.codehaus.jettison.json.JSONException;
 import org.codehaus.jettison.json.JSONObject;
-import org.hibernate.Query;
 import org.hibernate.criterion.Restrictions;
 import org.hibernate.exception.SQLGrammarException;
+import org.hibernate.query.Query;
 import org.openbravo.base.exception.OBException;
 import org.openbravo.base.exception.OBSecurityException;
 import org.openbravo.base.model.Entity;
@@ -508,23 +508,23 @@
               continue;
             }
             String referenceId = col.getReferenceSearchKey().getId();
-            Map<String, String> reflists = new HashMap<String, String>();
+            Map<String, String> reflists = new HashMap<>();
             final String hql = "select al.searchKey, al.name from ADList al where "
                 + " al.reference.id=:referenceId and al.active=true";
-            final Query qry = OBDal.getInstance().getSession().createQuery(hql);
+            final Query<Object[]> qry = OBDal.getInstance().getSession()
+                .createQuery(hql, Object[].class);
             qry.setParameter("referenceId", referenceId);
-            for (Object o : qry.list()) {
-              final Object[] row = (Object[]) o;
+            for (Object[] row : qry.list()) {
               reflists.put(row[0].toString(), row[1].toString());
             }
             final String hqltrl = "select al.searchKey, trl.name from ADList al, ADListTrl trl where "
                 + " al.reference.id=:referenceId and trl.listReference=al and trl.language.id=:languageId"
                 + " and al.active=true and trl.active=true";
-            final Query qrytrl = OBDal.getInstance().getSession().createQuery(hqltrl);
+            final Query<Object[]> qrytrl = OBDal.getInstance().getSession()
+                .createQuery(hqltrl, Object[].class);
             qrytrl.setParameter("referenceId", referenceId);
             qrytrl.setParameter("languageId", userLanguageId);
-            for (Object o : qrytrl.list()) {
-              final Object[] row = (Object[]) o;
+            for (Object[] row : qrytrl.list()) {
               reflists.put(row[0].toString(), row[1].toString());
             }
             refListCols.add(propKey);
--- a/modules/org.openbravo.service.datasource/src/org/openbravo/service/datasource/HQLDataSourceService.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/modules/org.openbravo.service.datasource/src/org/openbravo/service/datasource/HQLDataSourceService.java	Tue Jul 24 10:44:21 2018 +0200
@@ -23,16 +23,19 @@
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
+import java.util.Map.Entry;
 import java.util.Set;
 
 import javax.enterprise.inject.Any;
 import javax.enterprise.inject.Instance;
 import javax.inject.Inject;
+import javax.persistence.Tuple;
+import javax.persistence.TupleElement;
 
 import org.apache.commons.lang.StringUtils;
 import org.codehaus.jettison.json.JSONObject;
-import org.hibernate.Query;
 import org.hibernate.ScrollableResults;
+import org.hibernate.query.Query;
 import org.openbravo.base.exception.OBSecurityException;
 import org.openbravo.base.model.Entity;
 import org.openbravo.base.model.ModelProvider;
@@ -90,7 +93,7 @@
     // Returns the datasource properties, based on the columns of the table that is going to use the
     // datasource
     // This is needed to support client side filtering
-    List<DataSourceProperty> dataSourceProperties = new ArrayList<DataSourceProperty>();
+    List<DataSourceProperty> dataSourceProperties = new ArrayList<>();
     String tableId = (String) parameters.get("tableId");
     if (tableId != null) {
       Table table = OBDal.getInstance().get(Table.class, tableId);
@@ -149,7 +152,7 @@
   protected int getCount(Map<String, String> parameters) {
     Table table = getTableFromParameters(parameters);
     boolean justCount = true;
-    Query countQuery = getQuery(table, parameters, justCount);
+    Query<Tuple> countQuery = getQuery(table, parameters, justCount);
     String hqlQuery = countQuery.getQueryString();
     int nRows = -1;
     if (hqlQuery.toUpperCase().contains(GROUPBY)) {
@@ -157,12 +160,12 @@
       countQuery = getQuery(table, parameters, justCount);
       return getGroupedCount(countQuery);
     } else {
-      nRows = ((Number) countQuery.uniqueResult()).intValue();
+      nRows = ((Number) countQuery.uniqueResult().get(0)).intValue();
     }
     return nRows;
   }
 
-  protected int getGroupedCount(Query countQuery) {
+  protected int getGroupedCount(Query<Tuple> countQuery) {
     int nRows = -1;
     ScrollableResults scrollableResults = countQuery.scroll();
     if (scrollableResults.last()) {
@@ -180,7 +183,7 @@
     Entity entity = ModelProvider.getInstance().getEntityByTableId(table.getId());
     OBContext.setAdminMode(true);
     boolean justCount = false;
-    Query query = getQuery(table, parameters, justCount);
+    Query<Tuple> query = getQuery(table, parameters, justCount);
 
     if (startRow > 0) {
       query.setFirstResult(startRow);
@@ -191,38 +194,24 @@
 
     String distinct = parameters.get(JsonConstants.DISTINCT_PARAMETER);
     List<Column> columns = table.getADColumnList();
-    List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
-    String[] returnAliases = query.getReturnAliases();
-    boolean checkIsNotNull = false;
-    for (Object row : query.list()) {
-      Map<String, Object> record = new HashMap<String, Object>();
+    List<Map<String, Object>> data = new ArrayList<>();
+    for (Tuple tuple : query.list()) {
+      Map<String, Object> record = new HashMap<>();
       if (distinct != null) {
-        Object[] result = (Object[]) row;
         // the whole referenced BaseOBObject is stored in the first position of the result
-        BaseOBObject bob = (BaseOBObject) result[0];
+        BaseOBObject bob = (BaseOBObject) tuple.get(0);
         if (bob == null) {
           break;
         }
         record.put(JsonConstants.ID, bob.getId());
         record.put(JsonConstants.IDENTIFIER, IdentifierProvider.getInstance().getIdentifier(bob));
       } else {
-        Object[] properties = (Object[]) row;
-        for (int i = 0; i < returnAliases.length; i++) {
-          String aliasName = returnAliases[i];
-          String propertyName;
-          if (aliasName.contains(PROPERTY_FIELD_SEPARATOR)) {
-            propertyName = aliasName.replace(PROPERTY_FIELD_SEPARATOR,
-                JsonConstants.FIELD_SEPARATOR);
-          } else {
-            Property property = entity.getPropertyByColumnName(aliasName.toLowerCase(),
-                checkIsNotNull);
-            if (property == null) {
-              property = entity.getPropertyByColumnName(columns.get(i).getDBColumnName()
-                  .toLowerCase());
-            }
-            propertyName = property.getName();
-          }
-          record.put(propertyName, properties[i]);
+        int i = 0;
+        for (TupleElement<?> tupleElement : tuple.getElements()) {
+          String alias = tupleElement.getAlias();
+          String propertyName = getPropertyName(entity, alias, columns.get(i).getDBColumnName());
+          record.put(propertyName, alias != null ? tuple.get(alias) : tuple.get(i));
+          i++;
         }
       }
       data.add(record);
@@ -231,6 +220,21 @@
     return data;
   }
 
+  private String getPropertyName(Entity entity, String alias, String columnName) {
+    if (alias == null) {
+      return entity.getPropertyByColumnName(columnName.toLowerCase()).getName();
+    }
+    if (alias.contains(PROPERTY_FIELD_SEPARATOR)) {
+      return alias.replace(PROPERTY_FIELD_SEPARATOR, JsonConstants.FIELD_SEPARATOR);
+    }
+    boolean checkIsNotNull = false;
+    Property property = entity.getPropertyByColumnName(alias.toLowerCase(), checkIsNotNull);
+    if (property == null) {
+      property = entity.getPropertyByColumnName(columnName.toLowerCase());
+    }
+    return property.getName();
+  }
+
   /**
    * Returns the HQL table whose data is being fetched. It will be obtained either using the table
    * id, or the tab id
@@ -263,7 +267,7 @@
    * the query will just return the number of records that fulfill the criteria. If justCount is
    * false, the query will return all the actual records that fulfill the criteria
    */
-  private Query getQuery(Table table, Map<String, String> parameters, boolean justCount) {
+  private Query<Tuple> getQuery(Table table, Map<String, String> parameters, boolean justCount) {
     OBContext.setAdminMode(true);
     String hqlQuery = table.getHqlQuery();
     // obtains the where clause from the criteria, using the AdvancedQueryBuilder
@@ -351,9 +355,9 @@
     }
 
     log.debug("HQL query: {}", hqlQuery);
-    Query query = OBDal.getInstance().getSession().createQuery(hqlQuery);
+    Query<Tuple> query = OBDal.getInstance().getSession().createQuery(hqlQuery, Tuple.class);
 
-    StringBuffer paramsLog = new StringBuffer();
+    StringBuilder paramsLog = new StringBuilder();
 
     // sets the parameters of the query
     for (String key : queryNamedParameters.keySet()) {
@@ -527,7 +531,7 @@
       // look for the property name, replace it with the column alias
       Property property = entity.getPropertyByColumnName(column.getDBColumnName());
       // Map used to replace the property name used in the criteria with its alias
-      Map<String, String> replacementMap = new HashMap<String, String>();
+      Map<String, String> replacementMap = new HashMap<>();
       String propertyNameBefore = null;
       String propertyNameAfter = null;
       if (property.isPrimitive()) {
@@ -550,9 +554,9 @@
         addEntryToReplacementMap(replacementMap, propertyNameBefore, propertyNameAfter,
             table.getEntityAlias());
       }
-      for (String toBeReplaced : replacementMap.keySet()) {
-        updatedWhereClause = updatedWhereClause.replaceAll(toBeReplaced,
-            replacementMap.get(toBeReplaced));
+      for (Entry<String, String> replacement : replacementMap.entrySet()) {
+        updatedWhereClause = updatedWhereClause.replaceAll(replacement.getKey(),
+            replacement.getValue());
       }
     }
     return updatedWhereClause;
@@ -591,7 +595,7 @@
   private String addAdditionalFilters(Table table, String hqlQuery, String filterWhereClause,
       Map<String, String> parameters) {
     OBContext.setAdminMode(true);
-    StringBuffer additionalFilter = new StringBuffer();
+    StringBuilder additionalFilter = new StringBuilder();
     final String entityAlias = table.getEntityAlias();
 
     // replace the carriage returns and the tabulations with blanks
@@ -637,7 +641,7 @@
     return hqlQueryWithFilters;
   }
 
-  private void addFilterWhereClause(StringBuffer additionalFilter, String filterWhereClause) {
+  private void addFilterWhereClause(StringBuilder additionalFilter, String filterWhereClause) {
     if (!filterWhereClause.trim().isEmpty()) {
       additionalFilter.append(AND + removeLeadingWhere(filterWhereClause));
     }
--- a/modules/org.openbravo.service.json/src/org/openbravo/service/json/DataEntityQueryService.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/modules/org.openbravo.service.json/src/org/openbravo/service/json/DataEntityQueryService.java	Tue Jul 24 10:44:21 2018 +0200
@@ -26,9 +26,9 @@
 import org.apache.log4j.Logger;
 import org.codehaus.jettison.json.JSONException;
 import org.codehaus.jettison.json.JSONObject;
-import org.hibernate.Query;
 import org.hibernate.ScrollMode;
 import org.hibernate.ScrollableResults;
+import org.hibernate.query.Query;
 import org.openbravo.base.exception.OBException;
 import org.openbravo.base.model.Entity;
 import org.openbravo.base.model.ModelProvider;
@@ -110,7 +110,7 @@
    * @return a result which can be scrolled forward only and the results are not cached
    */
   public ScrollableResults scroll() {
-    final Query qry = buildOBQuery().createQuery();
+    final Query<BaseOBObject> qry = buildOBQuery().createQuery();
     qry.setFetchSize(1000);
     qry.setCacheable(false);
     return qry.scroll(ScrollMode.FORWARD_ONLY);
--- a/modules/org.openbravo.service.json/src/org/openbravo/service/json/DefaultJsonDataService.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/modules/org.openbravo.service.json/src/org/openbravo/service/json/DefaultJsonDataService.java	Tue Jul 24 10:44:21 2018 +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-2017 Openbravo SLU 
+ * All portions are Copyright (C) 2009-2018 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -220,9 +220,10 @@
           final JSONObject singleResult = new JSONObject();
           if (queryService.getSummaryFields().size() == 1) {
             singleResult.put(queryService.getSummaryFields().get(0), queryService.buildOBQuery()
-                .createQuery().uniqueResult());
+                .uniqueResultObject());
           } else {
-            final Object[] os = (Object[]) queryService.buildOBQuery().createQuery().uniqueResult();
+            final Object[] os = queryService.buildOBQuery().createQuery(Object[].class)
+                .uniqueResult();
             int i = 0;
             if (os != null && os.length > 0) {
               for (String key : queryService.getSummaryFields()) {
--- a/modules/org.openbravo.userinterface.selector/src/org/openbravo/userinterface/selector/CustomQuerySelectorDatasource.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/modules/org.openbravo.userinterface.selector/src/org/openbravo/userinterface/selector/CustomQuerySelectorDatasource.java	Tue Jul 24 10:44:21 2018 +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-2017 Openbravo SLU
+ * All portions are Copyright (C) 2011-2018 Openbravo SLU
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -32,14 +32,17 @@
 import java.util.List;
 import java.util.Map;
 
+import javax.persistence.Tuple;
+import javax.persistence.TupleElement;
+
 import org.apache.commons.lang.StringUtils;
 import org.apache.log4j.Logger;
 import org.codehaus.jettison.json.JSONArray;
 import org.codehaus.jettison.json.JSONException;
 import org.codehaus.jettison.json.JSONObject;
 import org.hibernate.Hibernate;
-import org.hibernate.Query;
 import org.hibernate.criterion.Restrictions;
+import org.hibernate.query.Query;
 import org.openbravo.base.model.ModelProvider;
 import org.openbravo.base.model.domaintype.BigDecimalDomainType;
 import org.openbravo.base.model.domaintype.BooleanDomainType;
@@ -81,10 +84,11 @@
     // creation of formats is done here because they are not thread safe
     final SimpleDateFormat xmlDateFormat = JsonUtils.createDateFormat();
     final SimpleDateFormat xmlDateTimeFormat = JsonUtils.createDateTimeFormat();
-    final List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
-    final List<Object> typedParameters = new ArrayList<Object>();
+    final List<Map<String, Object>> result = new ArrayList<>();
+    final List<Object> typedParameters = new ArrayList<>();
     // Defaulted to endRow + 2 to check for more records while scrolling.
-    int totalRows = endRow + 2, rowCount = 0;
+    int totalRows = endRow + 2;
+    int rowCount = 0;
 
     String selectorId = parameters.get(SelectorConstants.DS_REQUEST_SELECTOR_ID_PARAMETER);
 
@@ -109,11 +113,11 @@
       String sortBy = parameters.get("_sortBy");
       HQL += getSortClause(sortBy, sel);
 
-      Query selQuery = OBDal.getInstance().getSession().createQuery(HQL);
+      Query<Tuple> selQuery = OBDal.getInstance().getSession().createQuery(HQL, Tuple.class);
+
       for (int i = 0; i < typedParameters.size(); i++) {
         selQuery.setParameter(ALIAS_PREFIX + Integer.toString(i), typedParameters.get(i));
       }
-      String[] queryAliases = selQuery.getReturnAliases();
 
       if (startRow > 0) {
         selQuery.setFirstResult(startRow);
@@ -122,21 +126,15 @@
         selQuery.setMaxResults(endRow - startRow + 1);
       }
 
-      for (Object objResult : selQuery.list()) {
+      for (Tuple tuple : selQuery.list()) {
         rowCount++;
-        final Map<String, Object> data = new LinkedHashMap<String, Object>();
-        Object[] resultList = new Object[1];
-        if (objResult instanceof Object[]) {
-          resultList = (Object[]) objResult;
-        } else {
-          resultList[0] = objResult;
-        }
-
+        final Map<String, Object> data = new LinkedHashMap<>();
         for (SelectorField field : fields) {
           // TODO: throw an exception if the display expression doesn't match any returned alias.
-          for (int i = 0; i < queryAliases.length; i++) {
-            if (queryAliases[i].equals(field.getDisplayColumnAlias())) {
-              Object value = resultList[i];
+          for (TupleElement<?> tupleElement : tuple.getElements()) {
+            String alias = tupleElement.getAlias();
+            if (alias != null && alias.equals(field.getDisplayColumnAlias())) {
+              Object value = tuple.get(alias);
               if (value instanceof Date) {
                 value = xmlDateFormat.format(value);
               }
@@ -144,19 +142,17 @@
                 value = xmlDateTimeFormat.format(value);
                 value = JsonUtils.convertToCorrectXSDFormat((String) value);
               }
-              data.put(queryAliases[i], value);
+              data.put(alias, value);
             }
           }
         }
         result.add(data);
       }
-      if ("true".equals(parameters.get(JsonConstants.NOCOUNT_PARAMETER))) {
-        if (startRow < endRow) {
-          if (rowCount < endRow) {
-            totalRows = rowCount;
-          }
-          parameters.put(JsonConstants.RESPONSE_TOTALROWS, String.valueOf(totalRows));
+      if ("true".equals(parameters.get(JsonConstants.NOCOUNT_PARAMETER)) && startRow < endRow) {
+        if (rowCount < endRow) {
+          totalRows = rowCount;
         }
+        parameters.put(JsonConstants.RESPONSE_TOTALROWS, String.valueOf(totalRows));
       }
     } finally {
       OBContext.restorePreviousMode();
@@ -526,11 +522,14 @@
    *          order by.
    * @param sel
    *          The Selector that it is being used.
-   * @return The index of the query column related to the field.
+   * @return The index of the query column related to the field. Note that 0 will be returned if
+   *         there is no query column with an alias equal to the provided field name.
    */
   private int getFieldSortIndex(String fieldName, Selector sel) {
+    @SuppressWarnings("deprecation")
     final String[] queryAliases = OBDal.getInstance().getSession()
         .createQuery(sel.getHQL().replace(ADDITIONAL_FILTERS, "1=1")).getReturnAliases();
+
     for (int i = 0; i < queryAliases.length; i++) {
       if (queryAliases[i].equals(fieldName)) {
         return i + 1;
--- a/modules/org.openbravo.userinterface.selector/src/org/openbravo/userinterface/selector/model/domaintype/SelectorDomainType.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/modules/org.openbravo.userinterface.selector/src/org/openbravo/userinterface/selector/model/domaintype/SelectorDomainType.java	Tue Jul 24 10:44:21 2018 +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-2011 Openbravo SLU 
+ * All portions are Copyright (C) 2009-2018 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -22,10 +22,8 @@
 import java.util.List;
 
 import org.apache.log4j.Logger;
-import org.hibernate.Criteria;
 import org.hibernate.Session;
-import org.hibernate.criterion.Order;
-import org.hibernate.criterion.Restrictions;
+import org.hibernate.query.Query;
 import org.openbravo.base.model.Column;
 import org.openbravo.base.model.ModelProvider;
 import org.openbravo.base.model.Table;
@@ -45,7 +43,7 @@
 
   @Override
   public List<Class<?>> getClasses() {
-    List<Class<?>> listOfClasses = new ArrayList<Class<?>>();
+    List<Class<?>> listOfClasses = new ArrayList<>();
     listOfClasses.add(SelectorDefinition.class);
     listOfClasses.add(DatasourceDefinition.class);
     return listOfClasses;
@@ -57,9 +55,12 @@
 
     Session session = ModelProvider.getInstance().getSession();
 
-    final Criteria criteria = session.createCriteria(SelectorDefinition.class);
-    criteria.add(Restrictions.eq("referenceId", getReference().getId()));
-    final List<?> list = criteria.list();
+    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());
+    final List<SelectorDefinition> list = query.list();
     if (list.isEmpty()) {
       // a base reference
       if (getReference().getParentReference() == null) {
@@ -71,7 +72,7 @@
       log.warn("Reference " + getReference()
           + " has more than one selector definition, only one is really used");
     }
-    final SelectorDefinition selectorDefinition = (SelectorDefinition) list.get(0);
+    final SelectorDefinition selectorDefinition = list.get(0);
     Table table = selectorDefinition.getTable();
     if (table == null && selectorDefinition.getDatasourceDefinition() != null) {
       table = selectorDefinition.getDatasourceDefinition().getTable();
@@ -94,12 +95,14 @@
     }
   }
 
-  @SuppressWarnings("unchecked")
   private List<Column> readColumns(Session session, Table table) {
-    final Criteria c = session.createCriteria(Column.class);
-    c.addOrder(Order.asc("position"));
-    c.add(Restrictions.eq("table", table));
-    return c.list();
+    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);
+    return query.list();
   }
 
   /*
@@ -109,6 +112,7 @@
    * org.openbravo.base.model.domaintype.BaseForeignKeyDomainType#getForeignKeyColumn(java.lang.
    * String)
    */
+  @Override
   public Column getForeignKeyColumn(String columnName) {
     while (!column.isKey() && column.getDomainType() instanceof ForeignKeyDomainType) {
       column = ((ForeignKeyDomainType) column.getDomainType()).getForeignKeyColumn(column
@@ -125,6 +129,7 @@
    * org.openbravo.base.model.domaintype.BaseForeignKeyDomainType#getReferedTableName(java.lang.
    * String)
    */
+  @Override
   protected String getReferedTableName(String columnName) {
     return tableName;
   }
--- a/src-test/src/org/openbravo/advpaymentmngt/test/TestUtility.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src-test/src/org/openbravo/advpaymentmngt/test/TestUtility.java	Tue Jul 24 10:44:21 2018 +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-2016 Openbravo SLU
+ * All portions are Copyright (C) 2010-2018 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  *************************************************************************
@@ -27,6 +27,8 @@
 import java.util.HashMap;
 import java.util.List;
 
+import javax.persistence.PersistenceException;
+
 import org.apache.log4j.Logger;
 import org.hibernate.criterion.Restrictions;
 import org.openbravo.advpaymentmngt.dao.AdvPaymentMngtDao;
@@ -246,7 +248,7 @@
       // force dal commit to throw exception
       OBDal.getInstance().save(accountPay);
       OBDal.getInstance().flush();
-    } catch (org.hibernate.exception.GenericJDBCException e) {
+    } catch (PersistenceException e) {
       log.error(e);
       exception = true;
       OBDal.getInstance().rollbackAndClose();
--- a/src-test/src/org/openbravo/test/AllWebserviceTests.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src-test/src/org/openbravo/test/AllWebserviceTests.java	Tue Jul 24 10:44:21 2018 +0200
@@ -37,6 +37,7 @@
 import org.openbravo.test.datasource.ResetCookieOnLogin;
 import org.openbravo.test.datasource.SelectorFieldPropertySelectorDSTest;
 import org.openbravo.test.datasource.SelectorPickListFieldsDataSourceTest;
+import org.openbravo.test.datasource.SummaryFieldRequestTest;
 import org.openbravo.test.datasource.TestAllowUnpagedDatasourcePreference;
 import org.openbravo.test.datasource.TestCSVEncoding;
 import org.openbravo.test.datasource.TestComboDatasource;
@@ -96,7 +97,8 @@
     NonIdForeignKeyFilters.class, //
     ResetCookieOnLogin.class, //
     ETagGeneration.class, //
-    TestSelectorDefaultFilterActionHandler.class //
+    TestSelectorDefaultFilterActionHandler.class, //
+    SummaryFieldRequestTest.class //
 })
 public class AllWebserviceTests {
 }
--- a/src-test/src/org/openbravo/test/base/BaseTest.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src-test/src/org/openbravo/test/base/BaseTest.java	Tue Jul 24 10:44:21 2018 +0200
@@ -26,9 +26,6 @@
 import java.util.Map;
 import java.util.Random;
 
-import junit.framework.TestCase;
-import junit.framework.TestResult;
-
 import org.apache.log4j.Logger;
 import org.apache.log4j.PropertyConfigurator;
 import org.hibernate.criterion.Restrictions;
@@ -48,6 +45,9 @@
 import org.openbravo.exception.PoolNotFoundException;
 import org.openbravo.model.ad.access.User;
 
+import junit.framework.TestCase;
+import junit.framework.TestResult;
+
 /**
  * BaseTest class is deprecated. All test case that works with old notation, will be working
  * normally.
@@ -280,7 +280,7 @@
     if (userIds == null) {
       setTestUserContext();
 
-      String[] excludedUserIds = { "100", TEST_USER_ID };
+      Object[] excludedUserIds = { "100", TEST_USER_ID };
       OBCriteria<User> obc = OBDal.getInstance().createCriteria(User.class);
       obc.add(Restrictions.not(Restrictions.in(User.PROPERTY_ID, excludedUserIds)));
       obc.add(Restrictions.isNotEmpty(User.PROPERTY_ADUSERROLESLIST));
--- a/src-test/src/org/openbravo/test/base/OBBaseTest.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src-test/src/org/openbravo/test/base/OBBaseTest.java	Tue Jul 24 10:44:21 2018 +0200
@@ -398,9 +398,11 @@
     if (sqlFunctions == null || sqlFunctions.isEmpty()) {
       return true;
     }
-    @SuppressWarnings("unchecked")
     Map<String, SQLFunction> registeredFunctions = SessionFactoryController.getInstance()
         .getConfiguration().getSqlFunctions();
+    if (registeredFunctions == null) {
+      return false;
+    }
     for (String sqlFunction : sqlFunctions.keySet()) {
       if (!registeredFunctions.containsKey(sqlFunction)) {
         return false;
@@ -506,7 +508,7 @@
 
       String[] excludedUserIds = { "100", TEST_USER_ID };
       OBCriteria<User> obc = OBDal.getInstance().createCriteria(User.class);
-      obc.add(Restrictions.not(Restrictions.in(User.PROPERTY_ID, excludedUserIds)));
+      obc.add(Restrictions.not(Restrictions.in(User.PROPERTY_ID, (Object[]) excludedUserIds)));
       obc.add(Restrictions.isNotEmpty(User.PROPERTY_ADUSERROLESLIST));
 
       if (obc.count() == 0) {
--- a/src-test/src/org/openbravo/test/costing/utils/TestCostingUtils.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src-test/src/org/openbravo/test/costing/utils/TestCostingUtils.java	Tue Jul 24 10:44:21 2018 +0200
@@ -8,7 +8,7 @@
  * Software distributed under the License  is  distributed  on  an "AS IS"
  * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
  * License for the specific  language  governing  rights  and  limitations
- * under the License. 
+ * 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
@@ -41,8 +41,8 @@
 
 import org.apache.commons.lang.time.DateUtils;
 import org.codehaus.jettison.json.JSONObject;
-import org.hibernate.Query;
 import org.hibernate.criterion.Restrictions;
+import org.hibernate.query.Query;
 import org.openbravo.base.exception.OBException;
 import org.openbravo.base.provider.OBConfigFileProvider;
 import org.openbravo.base.provider.OBProvider;
@@ -3591,14 +3591,14 @@
   }
 
   // Get Cost Adjustments created for a product
-  @SuppressWarnings("unchecked")
   public static List<CostAdjustment> getCostAdjustment(String productId) {
     try {
       String myQuery = "SELECT DISTINCT t1 "
           + "FROM CostAdjustment t1 LEFT JOIN t1.costAdjustmentLineList t2 LEFT JOIN t2.inventoryTransaction t3 "
           + "WHERE t3.product.id = :productId " + "ORDER BY t1.documentNo";
-      Query query = OBDal.getInstance().getSession().createQuery(myQuery);
-      query.setString("productId", productId);
+      Query<CostAdjustment> query = OBDal.getInstance().getSession()
+          .createQuery(myQuery, CostAdjustment.class);
+      query.setParameter("productId", productId);
       List<CostAdjustment> costAdjustmentList = query.list();
       return costAdjustmentList.isEmpty() ? null : costAdjustmentList;
     } catch (Exception e) {
@@ -3607,15 +3607,15 @@
   }
 
   // Get Physical Inventory
-  @SuppressWarnings("unchecked")
   public static List<InventoryCount> getPhysicalInventory(String inventoryAmountUpdateId) {
     try {
       String myQuery = "SELECT t1 "
           + "FROM MaterialMgmtInventoryCount t1, InventoryAmountUpdate t2 LEFT JOIN t2.inventoryAmountUpdateLineList t3 LEFT JOIN t3.inventoryAmountUpdateLineInventoriesList t4 "
           + "WHERE (t4.initInventory = t1 OR t4.closeInventory = t1) AND t2.id = :inventoryAmountUpdateId "
           + "ORDER BY t1.name";
-      Query query = OBDal.getInstance().getSession().createQuery(myQuery);
-      query.setString("inventoryAmountUpdateId", inventoryAmountUpdateId);
+      Query<InventoryCount> query = OBDal.getInstance().getSession()
+          .createQuery(myQuery, InventoryCount.class);
+      query.setParameter("inventoryAmountUpdateId", inventoryAmountUpdateId);
       return query.list();
     } catch (Exception e) {
       throw new OBException(e);
@@ -3740,16 +3740,16 @@
     hql.append(" and tc.costAdjustmentLine is not null");
     if (landedCost != null && landedCost.getCostAdjustment() != null) {
       hql.append(" and tc.costAdjustmentLine.costAdjustment.id <> :costAdjusmentID");
-
     }
 
-    Query query = OBDal.getInstance().getSession().createQuery(hql.toString());
+    Query<BigDecimal> query = OBDal.getInstance().getSession()
+        .createQuery(hql.toString(), BigDecimal.class);
     query.setParameter("transactionID", transaction.getId());
     if (landedCost != null && landedCost.getCostAdjustment() != null) {
       query.setParameter("costAdjusmentID", landedCost.getCostAdjustment().getId());
     }
 
-    return (BigDecimal) query.uniqueResult();
+    return query.uniqueResult();
   }
 
   // Assert common fields in all tables
--- a/src-test/src/org/openbravo/test/dal/ADCachedMultiThreadTest.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src-test/src/org/openbravo/test/dal/ADCachedMultiThreadTest.java	Tue Jul 24 10:44:21 2018 +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-2014 Openbravo SLU 
+ * All portions are Copyright (C) 2013-2018 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -35,7 +35,7 @@
 
 import org.apache.log4j.Level;
 import org.hibernate.LazyInitializationException;
-import org.hibernate.Query;
+import org.hibernate.query.Query;
 import org.junit.Test;
 import org.openbravo.client.application.window.ApplicationDictionaryCachedStructures;
 import org.openbravo.client.kernel.KernelUtils;
@@ -168,7 +168,7 @@
     String hql = "select distinct f.tab.id " //
         + "from ADField f "//
         + "where f.column.table != f.tab.table";
-    Query qTabs = OBDal.getInstance().getSession().createQuery(hql);
+    Query<String> qTabs = OBDal.getInstance().getSession().createQuery(hql, String.class);
 
     // Force using cache even there are mods in dev
     HiddenObjectHelper.set(adcs, "useCache", true);
@@ -177,7 +177,6 @@
 
     ArrayList<Callable<Long>> threads = new ArrayList<Callable<Long>>();
 
-    @SuppressWarnings("unchecked")
     List<String> tabIds = qTabs.list();
     for (String tabId : tabIds) {
       threads.add(new TabLoader(adcs, tabId, false));
--- a/src-test/src/org/openbravo/test/dal/ComputedColumnsTest.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src-test/src/org/openbravo/test/dal/ComputedColumnsTest.java	Tue Jul 24 10:44:21 2018 +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-2014 Openbravo SLU
+ * All portions are Copyright (C) 2013-2018 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -28,7 +28,7 @@
 import org.codehaus.jettison.json.JSONObject;
 import org.hibernate.QueryException;
 import org.hibernate.criterion.Restrictions;
-import org.hibernate.engine.EntityKey;
+import org.hibernate.engine.spi.EntityKey;
 import org.hibernate.stat.SessionStatistics;
 import org.junit.Test;
 import org.openbravo.base.provider.OBProvider;
@@ -64,8 +64,7 @@
     Order order = (Order) qOrder.uniqueResult();
 
     // check it is in memory but computed columns are not already loaded
-    assertTrue("DAL Order loaded",
-        dalObjectLoaded(Order.ENTITY_NAME, order.getId()));
+    assertTrue("DAL Order loaded", dalObjectLoaded(Order.ENTITY_NAME, order.getId()));
     assertFalse("DAL Order computed columns shouldn't be loaded",
         dalObjectLoaded(Order_ComputedColumns.ENTITY_NAME, order.getId()));
 
@@ -130,8 +129,8 @@
     boolean thrown = false;
     try {
       qOrder.count();
-    } catch (QueryException e) {
-      thrown = e.getMessage().startsWith(EXCEPTION_MSG);
+    } catch (IllegalArgumentException e) {
+      thrown = e.getCause().getMessage().startsWith(EXCEPTION_MSG);
     }
 
     // ... it shouldn't be possible, proxy should be used to reach it
--- a/src-test/src/org/openbravo/test/dal/DalComplexQueryTestOrderLine.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src-test/src/org/openbravo/test/dal/DalComplexQueryTestOrderLine.java	Tue Jul 24 10:44:21 2018 +0200
@@ -24,8 +24,8 @@
 import java.util.Map;
 
 import org.apache.log4j.Logger;
-import org.hibernate.Query;
 import org.hibernate.Session;
+import org.hibernate.query.Query;
 import org.junit.Test;
 import org.openbravo.dal.service.OBDal;
 import org.openbravo.dal.service.OBQuery;
@@ -149,9 +149,9 @@
       final String hql = "select sum(quantity) from ProcurementPOInvoiceMatch "
           + "where goodsShipmentLine is not null and salesOrderLine=:orderLine";
       final Session session = OBDal.getInstance().getSession();
-      final Query query = session.createQuery(hql);
+      final Query<BigDecimal> query = session.createQuery(hql, BigDecimal.class);
       query.setParameter("orderLine", ol);
-      final BigDecimal sum = (BigDecimal) query.uniqueResult();
+      final BigDecimal sum = query.uniqueResult();
       log.debug(sum);
     }
   }
@@ -221,11 +221,10 @@
 
     // final Session session = OBDal.getInstance().getSession();
     // session.createQuery(hql.toString());
-    final Query query = OBDal.getInstance().getSession().createQuery(hql);
+    final Query<Object[]> query = OBDal.getInstance().getSession().createQuery(hql, Object[].class);
     query.setParameter("bpId", "1000017");
 
-    for (Object o : query.list()) {
-      final Object[] os = (Object[]) o;
+    for (Object[] os : query.list()) {
       for (Object result : os) {
         log.debug(result);
       }
--- a/src-test/src/org/openbravo/test/dal/DalPerformanceExampleTest.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src-test/src/org/openbravo/test/dal/DalPerformanceExampleTest.java	Tue Jul 24 10:44:21 2018 +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) 2012-2014 Openbravo SLU 
+ * All portions are Copyright (C) 2012-2018 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -22,12 +22,13 @@
 import java.util.List;
 import java.util.UUID;
 
-import org.hibernate.Query;
 import org.hibernate.ScrollMode;
 import org.hibernate.ScrollableResults;
-import org.hibernate.collection.PersistentBag;
+import org.hibernate.collection.internal.PersistentBag;
 import org.hibernate.proxy.HibernateProxy;
+import org.hibernate.query.Query;
 import org.junit.Assert;
+import org.junit.Ignore;
 import org.junit.Test;
 import org.openbravo.base.provider.OBProvider;
 import org.openbravo.dal.core.DalUtil;
@@ -158,19 +159,16 @@
     Assert.assertTrue(((HibernateProxy) category).getHibernateLazyInitializer().isUninitialized());
 
     // get the id and entityname in a way which does not load the object
-    final Object id = category.getId();
+    category.getId();
 
     // still unloaded
     Assert.assertTrue(((HibernateProxy) category).getHibernateLazyInitializer().isUninitialized());
 
     // now call a method directly on the object
-    final Object id2 = category.getId();
+    category.getName();
 
     // now it is loaded!
     Assert.assertFalse(((HibernateProxy) category).getHibernateLazyInitializer().isUninitialized());
-
-    // and the id's are the same ofcourse
-    Assert.assertEquals(id, id2);
   }
 
   /**
@@ -255,7 +253,8 @@
       final String queryStr = "from BusinessPartner as bp left join bp.businessPartnerCategory where bp.organization.id "
           + OBDal.getInstance().getReadableOrganizationsInClause();
 
-      final Query qry = OBDal.getInstance().getSession().createQuery(queryStr);
+      final Query<Object[]> qry = OBDal.getInstance().getSession()
+          .createQuery(queryStr, Object[].class);
       qry.setMaxResults(1000);
       final ScrollableResults scroller = qry.scroll(ScrollMode.FORWARD_ONLY);
       while (scroller.next()) {
@@ -289,6 +288,7 @@
    * Scrollable results
    */
   @Test
+  @Ignore("Example that creates 1000000 copies of an order")
   public void testInsertSalesOrders() {
     setTestUserContext();
     final int cnt = 100;
@@ -297,7 +297,7 @@
       names[i] = UUID.randomUUID().toString();
     }
     final Order baseOrder = OBDal.getInstance()
-        .get(Order.class, "FD4E0C67A9454A4D983BB2F4E0D3E8BC");
+        .get(Order.class, "00247EB519C941DDA87A7F5630421924");
     for (int i = 0; i < 1000000; i++) {
       final Order copy = (Order) DalUtil.copy(baseOrder, true, true);
       copy.getOrderLineTaxList().clear();
@@ -305,6 +305,8 @@
       for (OrderLine ol : copy.getOrderLineList()) {
         ol.getOrderLineTaxList().clear();
       }
+      copy.setPosted("N");
+      copy.setProcessed(false);
       OBDal.getInstance().save(copy);
       if ((i % 100) == 0) {
         OBDal.getInstance().flush();
--- a/src-test/src/org/openbravo/test/dal/DalPerformanceProxyTest.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src-test/src/org/openbravo/test/dal/DalPerformanceProxyTest.java	Tue Jul 24 10:44:21 2018 +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) 2012-2014 Openbravo SLU 
+ * All portions are Copyright (C) 2012-2018 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -36,6 +36,7 @@
 import org.openbravo.model.common.businesspartner.BusinessPartner;
 import org.openbravo.model.common.businesspartner.Category;
 import org.openbravo.model.common.enterprise.Organization;
+import org.openbravo.service.db.DalConnectionProvider;
 import org.openbravo.test.base.OBBaseTest;
 
 /**
@@ -105,8 +106,9 @@
     try {
       setTestAdminContext();
 
+      DalConnectionProvider dcp = new DalConnectionProvider(false);
       final StatelessSession session = SessionFactoryController.getInstance().getSessionFactory()
-          .openStatelessSession();
+          .openStatelessSession(dcp.getConnection());
       session.beginTransaction();
       for (int i = 0; i < CNT; i++) {
         BusinessPartner bp = OBProvider.getInstance().get(BusinessPartner.class);
--- a/src-test/src/org/openbravo/test/dal/DalQueryTest.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src-test/src/org/openbravo/test/dal/DalQueryTest.java	Tue Jul 24 10:44:21 2018 +0200
@@ -31,8 +31,8 @@
 import java.util.Map;
 
 import org.apache.log4j.Logger;
-import org.hibernate.Query;
 import org.hibernate.criterion.Restrictions;
+import org.hibernate.query.Query;
 import org.junit.FixMethodOrder;
 import org.junit.Test;
 import org.junit.runners.MethodSorters;
@@ -241,7 +241,7 @@
       final OBQuery<MaterialTransaction> obq = OBDal.getInstance().createQuery(
           MaterialTransaction.class,
           " order by " + MaterialTransaction.PROPERTY_PRODUCT + "." + Product.PROPERTY_NAME);
-      final Query qry = obq.createQuery();
+      final Query<MaterialTransaction> qry = obq.createQuery();
       qry.setMaxResults(pageSize);
       qry.setFirstResult(i * pageSize);
 
--- a/src-test/src/org/openbravo/test/dal/DalTest.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src-test/src/org/openbravo/test/dal/DalTest.java	Tue Jul 24 10:44:21 2018 +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-2017 Openbravo SLU 
+ * All portions are Copyright (C) 2008-2018 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):
  *   Martin Taal <martin.taal@openbravo.com>,
@@ -24,6 +24,7 @@
 
 import static org.hamcrest.CoreMatchers.equalTo;
 import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.notNullValue;
 import static org.hamcrest.Matchers.hasSize;
 import static org.hamcrest.Matchers.not;
 import static org.hamcrest.Matchers.nullValue;
@@ -35,10 +36,12 @@
 import static org.junit.Assert.fail;
 import static org.junit.Assume.assumeThat;
 
+import java.util.ArrayList;
 import java.util.List;
 
 import org.apache.log4j.Level;
 import org.apache.log4j.Logger;
+import org.hibernate.Hibernate;
 import org.hibernate.ObjectNotFoundException;
 import org.hibernate.criterion.Restrictions;
 import org.junit.FixMethodOrder;
@@ -58,6 +61,7 @@
 import org.openbravo.dal.service.OBDal;
 import org.openbravo.dal.service.OBQuery;
 import org.openbravo.database.ExternalConnectionPool;
+import org.openbravo.model.ad.access.User;
 import org.openbravo.model.ad.system.SystemInformation;
 import org.openbravo.model.common.businesspartner.BusinessPartner;
 import org.openbravo.model.common.businesspartner.Category;
@@ -85,7 +89,7 @@
   public ExpectedException thrown = ExpectedException.none();
 
   /**
-   * Test to assert save false in a null char(1) column - Part I
+   * Test to assert save false in a null char(1) column - Part I.
    */
   @Test
   public void testASaveBooleanValue1() {
@@ -99,7 +103,7 @@
   }
 
   /**
-   * Test to assert save false in a null char(1) column - Part II
+   * Test to assert save false in a null char(1) column - Part II.
    */
   @Test
   public void testBSaveBooleanValue2() {
@@ -659,6 +663,28 @@
     assertEquals(isoCode, EURO);
   }
 
+  /**
+   * Test to check deletion queries using OBQuery
+   */
+  @Test
+  public void canDeleteWithOBQuery() {
+    int deletions = 0;
+    try {
+      User user = getNewUser();
+      // save the new user...
+      OBDal.getInstance().save(user);
+      OBDal.getInstance().flush();
+      // ...and now delete it using an OBQuery instance
+      String hql = "id = :id";
+      OBQuery<User> query = OBDal.getInstance().createQuery(User.class, hql);
+      query.setNamedParameter("id", user.getId());
+      deletions = query.deleteQuery().executeUpdate();
+    } finally {
+      OBDal.getInstance().rollbackAndClose();
+    }
+    assertThat("Can delete business objects using OBQuery", deletions, equalTo(1));
+  }
+
   private String getISOCodeFromCurrencyId(String currencyId, boolean includeAlias) {
     String isoCode = null;
     try {
@@ -678,4 +704,126 @@
     }
     return isoCode;
   }
+
+  /**
+   * Test to check that an OBQuery using legacy-style query parameters ('?') can be executed
+   * properly.
+   */
+  @Test
+  @SuppressWarnings("deprecation")
+  public void testOBQueryWithLegacyStyleParameters() {
+    setTestUserContext();
+    String hql = "as c where c.iSOCode = ? and c.symbol = ?";
+    OBQuery<Currency> query = OBDal.getInstance().createQuery(Currency.class, hql);
+    List<Object> parameters = new ArrayList<>(2);
+    parameters.add(EURO);
+    parameters.add("€");
+    query.setParameters(parameters);
+    assertNotNull(query.uniqueResult());
+  }
+
+  /**
+   * Test to check that proxies are not initialized when retrieving their identifier.
+   */
+  @Test
+  public void proxyShouldNotBeInitialized() {
+    Currency euro = OBDal.getInstance().getProxy(Currency.class, EURO_ID);
+    euro.getId();
+    assertThat("Proxy is not initialized", Hibernate.isInitialized(euro), equalTo(false));
+  }
+
+  /**
+   * Test to check that proxies are initialized when retrieving a property different from the
+   * identifier.
+   */
+  @Test
+  public void proxyShouldBeInitialized() {
+    Currency euro = OBDal.getInstance().getProxy(Currency.class, EURO_ID);
+    euro.getISOCode();
+    assertThat("Proxy is not initialized", Hibernate.isInitialized(euro), equalTo(true));
+  }
+
+  /**
+   * Test to check that it is possible to retrieve the identifier of a proxy that references a
+   * non-existent record.
+   */
+  @Test
+  public void canRetrieveIdOfNonExistentProxy() {
+    final String nonExistingId = "_0";
+    Currency unknown = OBDal.getInstance().getProxy(Currency.class, nonExistingId);
+    assertThat("Can retrieve ID of non-existent Proxy", unknown.getId(), equalTo(nonExistingId));
+  }
+
+  /**
+   * Test to check that it is possible to use OBContext cached objects as the value for OBQuery
+   * parameters even if they have not been previously loaded into the session.
+   */
+  @Test
+  public void canUseOBContextParamNotPresentInSession() {
+    OBDal.getInstance().getSession().clear();
+    OBQuery<BusinessPartner> q = OBDal.getInstance().createQuery(BusinessPartner.class,
+        "as bp where bp.client = :client");
+    q.setNamedParameter("client", OBContext.getOBContext().getCurrentClient());
+    assertThat("Can use OBContext object as OBQuery parameter value", q.list(), notNullValue());
+  }
+
+  /**
+   * Test to verify that Hibernate's property nullability check is disabled when creating entities
+   * through DAL.
+   */
+  @Test
+  public void nullabilityCheckIsDisabled() {
+    User newUser = getNewUser();
+    OBContext.setAdminMode(true);
+    String userId = null;
+    try {
+      // We should be able to create the User without explicitly setting its not nullable
+      // properties like the "lastPasswordUpdate" property.
+      OBDal.getInstance().save(newUser);
+      OBDal.getInstance().flush();
+      userId = newUser.getId();
+    } catch (Exception ex) {
+      log.error("Could not create new user", ex);
+    } finally {
+      OBDal.getInstance().rollbackAndClose(); // do not need to persist the new User in DB
+      OBContext.restorePreviousMode();
+    }
+    assertThat("Created User without setting its not-nullable properties", userId, notNullValue());
+  }
+
+  private User getNewUser() {
+    final User newUser = OBProvider.getInstance().get(User.class);
+    newUser.setClient(OBContext.getOBContext().getCurrentClient());
+    newUser.setOrganization(OBContext.getOBContext().getCurrentOrganization());
+    newUser.setName("Name");
+    newUser.setDescription("Description");
+    newUser.setUsername("UserName");
+    newUser.setPassword("Password");
+    newUser.setDefaultLanguage(OBContext.getOBContext().getLanguage());
+    return newUser;
+  }
+
+  /**
+   * Test to verify that evict() does not fail when invoking it with an already evicted
+   * BaseOBObject.
+   */
+  @Test
+  public void evictAnEvictedObjectShouldNotFail() {
+    User user = getNewUser();
+    OBContext.setAdminMode(true);
+    boolean fail = false;
+    try {
+      OBDal.getInstance().save(user);
+      OBDal.getInstance().flush();
+      OBDal.getInstance().getSession().evict(user);
+      // This second evict has no effect but it should not fail
+      OBDal.getInstance().getSession().evict(user);
+    } catch (IllegalArgumentException iaex) {
+      fail = true;
+    } finally {
+      OBDal.getInstance().rollbackAndClose();
+      OBContext.restorePreviousMode();
+    }
+    assertThat("Can evict same BaseOBObject twice", fail, equalTo(false));
+  }
 }
--- a/src-test/src/org/openbravo/test/dal/HiddenUpdateTest.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src-test/src/org/openbravo/test/dal/HiddenUpdateTest.java	Tue Jul 24 10:44:21 2018 +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-2014 Openbravo SLU 
+ * All portions are Copyright (C) 2008-2018 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -22,12 +22,16 @@
 import static org.junit.Assert.fail;
 
 import java.io.Serializable;
-import java.util.Iterator;
 
 import org.hibernate.CallbackException;
 import org.hibernate.EmptyInterceptor;
+import org.hibernate.boot.Metadata;
+import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder;
 import org.hibernate.cfg.Configuration;
+import org.hibernate.engine.spi.SessionFactoryImplementor;
+import org.hibernate.integrator.spi.Integrator;
 import org.hibernate.mapping.PersistentClass;
+import org.hibernate.service.spi.SessionFactoryServiceRegistry;
 import org.hibernate.type.Type;
 import org.junit.Test;
 import org.openbravo.base.model.Entity;
@@ -40,6 +44,8 @@
 import org.openbravo.dal.service.OBDal;
 import org.openbravo.dal.xml.EntityXMLConverter;
 import org.openbravo.test.base.OBBaseTest;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 /**
  * Test for updates which can happen behind the scenes (but should not happen) if properties are
@@ -52,6 +58,8 @@
 
 public class HiddenUpdateTest extends OBBaseTest {
 
+  private static final Logger log = LoggerFactory.getLogger(HiddenUpdateTest.class);
+
   /**
    * Tests for hidden updates. Hidden updates can occur when a load/read of an entity also changes
    * the state, or that hibernate detects dirty in another way. Use the Hibernate Interceptor
@@ -59,40 +67,39 @@
    */
   @Test
   public void testHiddenUpdates() {
+
     setSystemAdministratorContext();
 
     final SessionFactoryController currentSFC = SessionFactoryController.getInstance();
     try {
+      // close session created with previous SessionFactoryController
+      SessionHandler.getInstance().commitAndClose();
+
       final SessionFactoryController newSFC = new LocalSessionFactoryController();
       SessionFactoryController.setInstance(newSFC);
       SessionFactoryController.getInstance().reInitialize();
-      SessionHandler.getInstance().commitAndClose();
 
-      // System.err.println(SessionFactoryController.getInstance().
-      // getMapping());
+      Metadata metadata = LocalMetadataExtractorIntegrator.getInstance().getMetadata();
 
-      final Configuration cfg = DalSessionFactoryController.getInstance().getConfiguration();
-
-      for (final Iterator<?> it = cfg.getClassMappings(); it.hasNext();) {
-        final PersistentClass pc = (PersistentClass) it.next();
+      log.info("Checking hidden updates...");
+      for (PersistentClass pc : metadata.getEntityBindings()) {
         final String entityName = pc.getEntityName();
 
         Entity entity = ModelProvider.getInstance().getEntity(entityName);
-        // can also ignore views as they will result in errors anyway and they are
-        // mapped as not updateable
+        // can also ignore views as they will result in errors anyway and they are mapped as not
+        // updateable
         if (entity.isHQLBased() || entity.isDataSourceBased() || entity.isView()) {
           continue;
         }
 
-        // read max 5 records from each type, should be enough to limit runtime of the test
-        // and still give good results.
+        log.info("Checking entity {}", entityName);
+        // read max 5 records from each type, should be enough to limit runtime of the test and
+        // still give good results.
         final OBCriteria<BaseOBObject> criteria = OBDal.getInstance().createCriteria(entityName);
         criteria.setMaxResults(5);
         for (final Object o : criteria.list()) {
           if (o == null) {
-            // can occur when reading views which have nullable
-            // columns in a
-            // multi-column pk
+            // can occur when reading views which have nullable columns in a multi-column pk
             continue;
           }
           EntityXMLConverter.newInstance().toXML((BaseOBObject) o);
@@ -101,11 +108,19 @@
       }
     } finally {
       SessionFactoryController.setInstance(currentSFC);
+      SessionFactoryController.getInstance().reInitialize();
     }
+
   }
 
   private class LocalSessionFactoryController extends DalSessionFactoryController {
     @Override
+    public Configuration buildConfiguration() {
+      return new Configuration(new BootstrapServiceRegistryBuilder().applyIntegrator(
+          LocalMetadataExtractorIntegrator.getInstance()).build());
+    }
+
+    @Override
     protected void setInterceptor(Configuration configuration) {
       configuration.setInterceptor(new LocalInterceptor());
     }
@@ -156,4 +171,35 @@
       fail();
     }
   }
+
+  private static class LocalMetadataExtractorIntegrator implements Integrator {
+
+    private static LocalMetadataExtractorIntegrator instance = new LocalMetadataExtractorIntegrator();
+
+    private Metadata metadata;
+
+    public static LocalMetadataExtractorIntegrator getInstance() {
+      return instance;
+    }
+
+    public Metadata getMetadata() {
+      return metadata;
+    }
+
+    @Override
+    public void integrate(Metadata md, SessionFactoryImplementor sessionFactory,
+        SessionFactoryServiceRegistry serviceRegistry) {
+      if (this.metadata != null) {
+        return;
+      }
+      this.metadata = md;
+    }
+
+    @Override
+    public void disintegrate(SessionFactoryImplementor sessionFactory,
+        SessionFactoryServiceRegistry serviceRegistry) {
+      // Do not require to implement
+    }
+
+  }
 }
\ No newline at end of file
--- a/src-test/src/org/openbravo/test/dal/IssuesTest.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src-test/src/org/openbravo/test/dal/IssuesTest.java	Tue Jul 24 10:44:21 2018 +0200
@@ -37,18 +37,20 @@
 import java.util.Map;
 import java.util.Set;
 
+import javax.persistence.Tuple;
+
 import org.apache.log4j.Logger;
 import org.codehaus.jettison.json.JSONObject;
 import org.dom4j.Document;
 import org.dom4j.io.SAXReader;
-import org.hibernate.Query;
-import org.hibernate.SQLQuery;
 import org.hibernate.ScrollMode;
 import org.hibernate.ScrollableResults;
 import org.hibernate.Session;
 import org.hibernate.criterion.Restrictions;
 import org.hibernate.dialect.function.SQLFunction;
 import org.hibernate.dialect.function.StandardSQLFunction;
+import org.hibernate.query.NativeQuery;
+import org.hibernate.query.Query;
 import org.hibernate.type.StandardBasicTypes;
 import org.junit.Assert;
 import org.junit.Ignore;
@@ -66,6 +68,7 @@
 import org.openbravo.dal.core.DalUtil;
 import org.openbravo.dal.core.OBContext;
 import org.openbravo.dal.core.OBInterceptor;
+import org.openbravo.dal.core.SessionHandler;
 import org.openbravo.dal.security.OrganizationStructureProvider;
 import org.openbravo.dal.service.OBCriteria;
 import org.openbravo.dal.service.OBDal;
@@ -196,10 +199,9 @@
     final Session session = OBDal.getInstance().getSession();
     final String qryStr = "select bc.id, ad_column_identifier_std('C_BP_Group', bc.id) from "
         + Category.ENTITY_NAME + " bc";
-    final Query qry = session.createQuery(qryStr);
-    for (Object o : qry.list()) {
-      final Object[] os = (Object[]) o;
-      assertTrue(os[1] instanceof String && os[1].toString().length() > 0);
+    final Query<Tuple> qry = session.createQuery(qryStr, Tuple.class);
+    for (Tuple tuple : qry.list()) {
+      assertTrue(tuple.get(1) instanceof String && tuple.get(1).toString().length() > 0);
     }
   }
 
@@ -660,7 +662,9 @@
 
       @Override
       protected void doAction() throws Exception {
-        OBDal.getInstance().getSession().beginTransaction();
+        if (!SessionHandler.getInstance().isCurrentTransactionActive()) {
+          OBDal.getInstance().getSession().beginTransaction();
+        }
         OBDal.getInstance().getSession().getTransaction().commit();
       }
     };
@@ -712,8 +716,9 @@
     setSystemAdministratorContext();
 
     final Session session = OBDal.getInstance().getSession();
-    SQLQuery query = session
-        .createSQLQuery("SELECT AD_REF_LIST.VALUE AS VALUE, AD_REF_LIST.NAME AS LISTNAME, TRL.NAME AS TRLNAME "
+    @SuppressWarnings("rawtypes")
+    NativeQuery query = session
+        .createNativeQuery("SELECT AD_REF_LIST.VALUE AS VALUE, AD_REF_LIST.NAME AS LISTNAME, TRL.NAME AS TRLNAME "
             + "FROM AD_REF_LIST LEFT OUTER JOIN "
             + "(SELECT AD_REF_LIST_ID, NAME FROM AD_REF_LIST_TRL WHERE AD_REF_LIST_TRL.AD_LANGUAGE = :language) TRL "
             + "ON AD_REF_LIST.AD_REF_LIST_ID = TRL.AD_REF_LIST_ID "
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src-test/src/org/openbravo/test/datasource/SummaryFieldRequestTest.java	Tue Jul 24 10:44:21 2018 +0200
@@ -0,0 +1,101 @@
+/*
+ *************************************************************************
+ * The contents of this file are subject to the Openbravo  Public  License
+ * Version  1.1  (the  "License"),  being   the  Mozilla   Public  License
+ * Version 1.1  with a permitted attribution clause; you may not  use this
+ * file except in compliance with the License. You  may  obtain  a copy of
+ * the License at http://www.openbravo.com/legal/license.html 
+ * Software distributed under the License  is  distributed  on  an "AS IS"
+ * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
+ * License for the specific  language  governing  rights  and  limitations
+ * 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 Rights Reserved. 
+ * Contributor(s):  ______________________________________.
+ ************************************************************************
+ */
+package org.openbravo.test.datasource;
+
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.hamcrest.CoreMatchers.notNullValue;
+import static org.junit.Assert.assertThat;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.codehaus.jettison.json.JSONObject;
+import org.junit.Test;
+import org.openbravo.dal.core.OBContext;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Test cases for grid summaries
+ */
+public class SummaryFieldRequestTest extends BaseDataSourceTestDal {
+  private static final Logger log = LoggerFactory.getLogger(SummaryFieldRequestTest.class);
+
+  /**
+   * Test that a single summary function can be requested properly
+   */
+  @Test
+  public void summaryFunctionIsCalculated() {
+    OBContext.setOBContext(TEST_USER_ID);
+    try {
+      JSONObject summaryFunction = new JSONObject();
+      summaryFunction.put("grandTotalAmount", "sum");
+      JSONObject gridSummaries = getGridSummaries(summaryFunction);
+      assertThat("Summary field sum(grandTotalAmount) is calculated",
+          gridSummaries.getDouble("grandTotalAmount"), notNullValue());
+    } catch (Exception ex) {
+      log.error("Error executing request to calculate the summary function", ex);
+    }
+  }
+
+  /**
+   * Test that multiple summary functions can be requested properly
+   */
+  @Test
+  public void summaryFunctionsAreCalculated() {
+    OBContext.setOBContext(TEST_USER_ID);
+    try {
+      JSONObject summaryFunctions = new JSONObject();
+      summaryFunctions.put("documentNo", "max");
+      summaryFunctions.put("grandTotalAmount", "sum");
+      JSONObject gridSummaries = getGridSummaries(summaryFunctions);
+      assertThat("Summary field max(documentNo) is calculated",
+          gridSummaries.getString("documentNo"), notNullValue());
+      assertThat("Summary field sum(grandTotalAmount) is calculated",
+          gridSummaries.getDouble("grandTotalAmount"), notNullValue());
+    } catch (Exception ex) {
+      log.error("Error executing request to calculate summary functions", ex);
+    }
+  }
+
+  private JSONObject getGridSummaries(JSONObject summaryFunctions) throws Exception {
+    Map<String, String> params = new HashMap<String, String>();
+
+    params.put("_summary", summaryFunctions.toString());
+    params.put("_noCount", "true");
+    params.put("_operationType", "fetch");
+    params.put("_startRow", "0");
+    params.put("_endRow", "1");
+
+    JSONObject resp = new JSONObject(doRequest("/org.openbravo.service.datasource/Order", params,
+        200, "POST"));
+
+    assertThat("expecting response, got: " + resp, resp.has("response"), equalTo(true));
+
+    JSONObject r = resp.getJSONObject("response");
+    log.debug("Response: {}", r);
+    assertThat("expecting data in response, got: " + r, r.has("data"), equalTo(true));
+
+    JSONObject data = r.getJSONArray("data").getJSONObject(0);
+    assertThat("Is Grid Summary", data.getBoolean("isGridSummary"), equalTo(true));
+
+    return data;
+  }
+
+}
\ No newline at end of file
--- a/src-test/src/org/openbravo/test/db/model/functions/ADOrgTreeTest.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src-test/src/org/openbravo/test/db/model/functions/ADOrgTreeTest.java	Tue Jul 24 10:44:21 2018 +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 Openbravo SLU
+ * All portions are Copyright (C) 2017-2018 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  *************************************************************************
@@ -31,8 +31,8 @@
 
 import org.apache.commons.lang.StringUtils;
 import org.apache.log4j.Logger;
-import org.hibernate.Query;
 import org.hibernate.Session;
+import org.hibernate.query.Query;
 import org.junit.Ignore;
 import org.junit.Test;
 import org.openbravo.base.session.OBPropertiesProvider;
@@ -290,16 +290,16 @@
       OBContext.setAdminMode(true);
       final String hql = "select count(*) from FinancialMgmtAccountingFact fa where ad_isorgincluded(fa.organization.id, :parentOrgId, :clientId) <> -1";
       final Session session = OBDal.getInstance().getSession();
-      final Query hqlQuery = session.createQuery(hql.toString());
+      final Query<Long> hqlQuery = session.createQuery(hql.toString(), Long.class);
       hqlQuery.setParameter("parentOrgId", ORG_FB_SPAIN);
       hqlQuery.setParameter("clientId", CLIENT_FB);
       long start = System.currentTimeMillis();
-      final long hqlCount = (long) hqlQuery.uniqueResult();
+      final long hqlCount = hqlQuery.uniqueResult();
       long hqlTime = System.currentTimeMillis() - start;
       log.info("AD_IsOrgIncluded time: " + hqlTime);
 
       final String hqlLegacy = "select count(*) from FinancialMgmtAccountingFact fa where ad_isorgincluded_treenode(fa.organization.id, :parentOrgId, :clientId) <> -1";
-      final Query hqlLegacyQuery = session.createQuery(hqlLegacy.toString());
+      final Query<Long> hqlLegacyQuery = session.createQuery(hqlLegacy.toString(), Long.class);
       hqlLegacyQuery.setParameter("parentOrgId", ORG_FB_SPAIN);
       hqlLegacyQuery.setParameter("clientId", CLIENT_FB);
       start = System.currentTimeMillis();
--- a/src-test/src/org/openbravo/test/db/model/triggers/M_inoutlinetrgTest.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src-test/src/org/openbravo/test/db/model/triggers/M_inoutlinetrgTest.java	Tue Jul 24 10:44:21 2018 +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 Openbravo SLU
+ * All portions are Copyright (C) 2015-2018 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -26,7 +26,7 @@
 import java.util.Date;
 import java.util.List;
 
-import org.hibernate.Query;
+import org.hibernate.query.Query;
 import org.junit.Test;
 import org.openbravo.base.exception.OBException;
 import org.openbravo.base.provider.OBProvider;
@@ -593,8 +593,9 @@
     final StringBuffer hqlString = new StringBuffer();
     hqlString
         .append(" delete from MaterialMgmtShipmentInOutLine where shipmentReceipt.id = :mInOutId ");
+    @SuppressWarnings("rawtypes")
     Query deleteQry = OBDal.getInstance().getSession().createQuery(hqlString.toString());
-    deleteQry.setString("mInOutId", inOut.getId());
+    deleteQry.setParameter("mInOutId", inOut.getId());
     deleteQry.executeUpdate();
     OBDal.getInstance().getConnection().commit();
     OBDal.getInstance().refresh(inOut);
@@ -628,7 +629,8 @@
       hqlString.append(" and sd.orderUOM.id is null ");
     }
 
-    Query query = OBDal.getInstance().getSession().createQuery(hqlString.toString());
+    Query<StorageDetail> query = OBDal.getInstance().getSession()
+        .createQuery(hqlString.toString(), StorageDetail.class);
     query.setParameter("productId", _product.getId());
     query.setParameter("locatorId", _locator.getId());
     query.setParameter("uomId", uom.getId());
@@ -638,9 +640,9 @@
     }
     query.setMaxResults(1);
 
-    List<?> queryList = query.list();
+    List<StorageDetail> queryList = query.list();
     if (!queryList.isEmpty()) {
-      return (StorageDetail) queryList.get(0);
+      return queryList.get(0);
     }
     return null;
   }
--- a/src-test/src/org/openbravo/test/model/ClassLoaderTest.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src-test/src/org/openbravo/test/model/ClassLoaderTest.java	Tue Jul 24 10:44:21 2018 +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-2016 Openbravo SLU
+ * All portions are Copyright (C) 2010-2018 Openbravo SLU
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -91,7 +91,7 @@
     // "F" - "Filter"
     // "R" - "Resource"
 
-    final String[] in = { "L", "F" };
+    final Object[] in = { "L", "F" };
 
     // Checking listener and filters classes
     OBCriteria<ModelImplementation> obc = OBDal.getInstance().createCriteria(
--- a/src-test/src/org/openbravo/test/model/RuntimeModelTest.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src-test/src/org/openbravo/test/model/RuntimeModelTest.java	Tue Jul 24 10:44:21 2018 +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-2014 Openbravo SLU 
+ * All portions are Copyright (C) 2008-2018 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -29,10 +29,9 @@
 import java.util.List;
 
 import org.apache.log4j.Logger;
-import org.hibernate.Criteria;
+import org.hibernate.Session;
 import org.hibernate.Transaction;
-import org.hibernate.classic.Session;
-import org.hibernate.criterion.Order;
+import org.hibernate.query.Query;
 import org.junit.Before;
 import org.junit.Test;
 import org.openbravo.base.model.Column;
@@ -374,10 +373,11 @@
     try {
       final List<Table> tables = ModelProvider.getInstance().list(session, Table.class);
       // read the columns in one query and assign them to the table
-      final Criteria c = session.createCriteria(Column.class);
-      c.addOrder(Order.asc("position"));
-      @SuppressWarnings("unchecked")
-      final List<Column> cols = c.list();
+      StringBuilder hql = new StringBuilder();
+      hql.append("SELECT c FROM " + Column.class.getName() + " AS c");
+      hql.append(" ORDER BY c.position ASC");
+      Query<Column> query = session.createQuery(hql.toString(), Column.class);
+      final List<Column> cols = query.list();
       for (final Column column : cols) {
         final Table table = column.getTable();
         table.getColumns().add(column);
--- a/src-test/src/org/openbravo/test/modularity/DBPrefixTest.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src-test/src/org/openbravo/test/modularity/DBPrefixTest.java	Tue Jul 24 10:44:21 2018 +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-2014 Openbravo SLU 
+ * All portions are Copyright (C) 2009-2018 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -25,6 +25,8 @@
 
 import java.util.List;
 
+import javax.persistence.PersistenceException;
+
 import org.hibernate.criterion.Restrictions;
 import org.junit.FixMethodOrder;
 import org.junit.Test;
@@ -154,18 +156,15 @@
       OBDal.getInstance().remove(dbPrefix);
       OBDal.getInstance().commitAndClose();
       // thrown when using pgsql
-    } catch (org.hibernate.exception.GenericJDBCException e) {
-      exception = true;
-      OBDal.getInstance().rollbackAndClose();
-      // thrown when using oracle
-    } catch (org.hibernate.QueryTimeoutException e) {
+    } catch (PersistenceException e) {
       exception = true;
       OBDal.getInstance().rollbackAndClose();
     }
-    if (isValid)
+    if (isValid) {
       assertFalse("Not inserted a valid prefix:" + name, exception);
-    else
+    } else {
       assertTrue("Inserted a non-valid prefix:" + name, exception);
+    }
     OBDal.getInstance().flush();
   }
 }
--- a/src-test/src/org/openbravo/test/modularity/TableNameTest.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src-test/src/org/openbravo/test/modularity/TableNameTest.java	Tue Jul 24 10:44:21 2018 +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-2014 Openbravo SLU 
+ * All portions are Copyright (C) 2009-2018 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -23,10 +23,10 @@
 
 import java.util.List;
 
+import javax.persistence.PersistenceException;
+
 import org.apache.log4j.Logger;
-import org.hibernate.QueryTimeoutException;
 import org.hibernate.criterion.Restrictions;
-import org.hibernate.exception.GenericJDBCException;
 import org.junit.FixMethodOrder;
 import org.junit.Test;
 import org.junit.runners.MethodSorters;
@@ -115,9 +115,7 @@
       // force dal commit to throw exception
       commitTransaction();
       fail("Saved table but it shouldn't be");
-    } catch (GenericJDBCException e) { // thrown on pgsql
-      rollback();
-    } catch (QueryTimeoutException e) { // thrown on oracle
+    } catch (PersistenceException e) {
       rollback();
     }
   }
@@ -141,9 +139,7 @@
       // force dal commit to throw exception
       commitTransaction();
       fail("Saved table but it shouldn't be");
-    } catch (GenericJDBCException e) { // thrown on pgsql
-      rollback();
-    } catch (QueryTimeoutException e) { // thrown on oracle
+    } catch (PersistenceException e) {
       rollback();
     }
   }
@@ -165,9 +161,7 @@
       // force dal commit to throw exception
       commitTransaction();
       fail("Saved table but it shouldn't be");
-    } catch (GenericJDBCException e) { // thrown on pgsql
-      rollback();
-    } catch (QueryTimeoutException e) { // thrown on oracle
+    } catch (PersistenceException e) {
       rollback();
     }
   }
--- a/src-test/src/org/openbravo/test/security/UserInfoSessionDataTest.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src-test/src/org/openbravo/test/security/UserInfoSessionDataTest.java	Tue Jul 24 10:44:21 2018 +0200
@@ -33,8 +33,8 @@
 import org.codehaus.jettison.json.JSONArray;
 import org.codehaus.jettison.json.JSONException;
 import org.codehaus.jettison.json.JSONObject;
-import org.hibernate.Query;
 import org.hibernate.criterion.Restrictions;
+import org.hibernate.query.Query;
 import org.junit.AfterClass;
 import org.junit.BeforeClass;
 import org.junit.Test;
@@ -247,7 +247,6 @@
     return ids;
   }
 
-  @SuppressWarnings("unchecked")
   private List<String> getAccessibleWarehousesIds(String clientId, String orgId)
       throws JSONException {
     OrganizationStructureProvider osp = OBContext.getOBContext().getOrganizationStructureProvider(
@@ -255,10 +254,11 @@
     final StringBuilder hql = new StringBuilder();
     hql.append("select w.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");
-    Query orgWarehouses = OBDal.getInstance().getSession().createQuery(hql.toString());
+    Query<String> orgWarehouses = OBDal.getInstance().getSession()
+        .createQuery(hql.toString(), String.class);
     orgWarehouses.setParameterList("orgList", osp.getNaturalTree(orgId));
-    orgWarehouses.setString("clientId", clientId);
-    return (List<String>) orgWarehouses.list();
+    orgWarehouses.setParameter("clientId", clientId);
+    return orgWarehouses.list();
   }
 
   private JSONObject getUserInfo(String resp) {
--- a/src-test/src/org/openbravo/test/system/SystemValidatorTest.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src-test/src/org/openbravo/test/system/SystemValidatorTest.java	Tue Jul 24 10:44:21 2018 +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-2016 Openbravo SLU 
+ * All portions are Copyright (C) 2009-2018 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -27,8 +27,8 @@
 import java.util.List;
 
 import org.apache.log4j.Logger;
-import org.hibernate.Query;
 import org.hibernate.criterion.Restrictions;
+import org.hibernate.query.Query;
 import org.junit.Test;
 import org.openbravo.dal.service.OBCriteria;
 import org.openbravo.dal.service.OBDal;
@@ -117,6 +117,7 @@
       return;
     }
 
+    @SuppressWarnings("rawtypes")
     Query upd = OBDal.getInstance().getSession()
         .createQuery("update ADModule set inDevelopment = false where id in (:mods)");
     upd.setParameterList("mods", updatedModules);
--- a/src-test/src/org/openbravo/test/taxes/TaxesTest.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src-test/src/org/openbravo/test/taxes/TaxesTest.java	Tue Jul 24 10:44:21 2018 +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-2017 Openbravo SLU 
+ * All portions are Copyright (C) 2015-2018 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -32,8 +32,8 @@
 import java.util.HashMap;
 import java.util.List;
 
-import org.hibernate.Query;
 import org.hibernate.criterion.Restrictions;
+import org.hibernate.query.Query;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.junit.runners.Parameterized;
@@ -706,6 +706,7 @@
       update.append(" update " + TaxRate.ENTITY_NAME);
       update.append(" set " + TaxRate.PROPERTY_DOCTAXAMOUNT + " = :docTax");
       update.append(" where " + TaxRate.PROPERTY_CLIENT + ".id = :clientId");
+      @SuppressWarnings("rawtypes")
       Query updateQry = OBDal.getInstance().getSession().createQuery(update.toString());
       updateQry.setParameter("docTax", isStart ? "L" : "D");
       updateQry.setParameter("clientId", CLIENT_ID);
--- a/src-test/src/org/openbravo/test/views/ETagGeneration.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src-test/src/org/openbravo/test/views/ETagGeneration.java	Tue Jul 24 10:44:21 2018 +0200
@@ -28,7 +28,7 @@
 
 import javax.servlet.http.HttpServletResponse;
 
-import org.hibernate.Query;
+import org.hibernate.query.Query;
 import org.junit.Test;
 import org.openbravo.dal.service.OBDal;
 import org.openbravo.erpCommon.businessUtility.Preferences;
@@ -83,8 +83,8 @@
   }
 
   private Boolean hasModulesInDevelopment() {
-    final Query indevelMods = OBDal.getInstance().getSession()
-        .createQuery("select 1 from ADModule m where m.inDevelopment=true");
+    final Query<Object> indevelMods = OBDal.getInstance().getSession()
+        .createQuery("select 1 from ADModule m where m.inDevelopment=true", Object.class);
     indevelMods.setMaxResults(1);
     return indevelMods.list().size() > 0;
   }
--- a/src-test/src/org/openbravo/test/xml/EntityXMLImportTestReference.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src-test/src/org/openbravo/test/xml/EntityXMLImportTestReference.java	Tue Jul 24 10:44:21 2018 +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-2014 Openbravo SLU 
+ * All portions are Copyright (C) 2008-2018 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -26,9 +26,8 @@
 import java.util.ArrayList;
 import java.util.List;
 
-import org.hibernate.Criteria;
-import org.hibernate.criterion.Criterion;
 import org.hibernate.criterion.Restrictions;
+import org.hibernate.query.Query;
 import org.junit.Before;
 import org.junit.Ignore;
 import org.junit.Test;
@@ -37,6 +36,7 @@
 import org.openbravo.dal.core.SessionHandler;
 import org.openbravo.dal.service.OBCriteria;
 import org.openbravo.dal.service.OBDal;
+import org.openbravo.erpCommon.utility.StringCollectionUtils;
 import org.openbravo.model.ad.system.Client;
 import org.openbravo.model.ad.utility.ReferenceDataStore;
 import org.openbravo.model.common.enterprise.Organization;
@@ -137,8 +137,8 @@
     // deleted, force this by being admin
     OBContext.setAdminMode();
     try {
-      removeAll(Warehouse.class, numberOfWarehouses,
-          Restrictions.in(Warehouse.PROPERTY_NAME, warehouseNames));
+      removeAll(Warehouse.class, numberOfWarehouses, "e." + Warehouse.PROPERTY_NAME + " IN ("
+          + StringCollectionUtils.commaSeparated(warehouseNames) + ")");
     } finally {
       OBContext.restorePreviousMode();
     }
@@ -189,28 +189,33 @@
     // deleted, force this by being admin
     OBContext.setAdminMode();
     try {
-      removeAll(Warehouse.class, numberOfWarehouses,
-          Restrictions.in(Warehouse.PROPERTY_NAME, warehouseNames));
-      removeAll(Location.class, numberOfLocations,
-          Restrictions.in(Location.PROPERTY_ADDRESSLINE1, locationAddresses));
+      removeAll(Warehouse.class, numberOfWarehouses, "e." + Warehouse.PROPERTY_NAME + " IN ("
+          + StringCollectionUtils.commaSeparated(warehouseNames) + ")");
+      removeAll(Location.class, numberOfLocations, "e." + Location.PROPERTY_ADDRESSLINE1 + " IN ("
+          + StringCollectionUtils.commaSeparated(locationAddresses) + ")");
     } finally {
       OBContext.restorePreviousMode();
     }
   }
 
-  private <T extends BaseOBObject> void removeAll(Class<T> clz, int expectCount, Criterion c) {
-    final Criteria criteria = SessionHandler.getInstance().getSession().createCriteria(clz);
-    if (c != null) {
-      criteria.add(c);
+  private <T extends BaseOBObject> void removeAll(Class<T> clz, int expectCount,
+      String additionalWhereClause) {
+    StringBuilder hql = new StringBuilder();
+    hql.append("SELECT e FROM " + clz.getName() + " AS e");
+    hql.append(" WHERE e.client.id = :clientId");
+    if (additionalWhereClause != null) {
+      hql.append(" AND " + additionalWhereClause);
     }
-    criteria.add(Restrictions.eq("client.id", QA_TEST_CLIENT_ID));
 
-    @SuppressWarnings("unchecked")
-    final List<T> list = criteria.list();
+    Query<BaseOBObject> query = SessionHandler.getInstance().getSession()
+        .createQuery(hql.toString(), BaseOBObject.class);
+    query.setParameter("clientId", QA_TEST_CLIENT_ID);
+
+    final List<BaseOBObject> list = query.list();
     if (expectCount != -1) {
       assertEquals(expectCount, list.size());
     }
-    for (final T t : list) {
+    for (final BaseOBObject t : list) {
       SessionHandler.getInstance().getSession().delete(t);
     }
   }
--- a/src/org/openbravo/base/model/ModelProvider.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/base/model/ModelProvider.java	Tue Jul 24 10:44:21 2018 +0200
@@ -30,13 +30,15 @@
 import java.util.List;
 import java.util.Map;
 
+import javax.persistence.criteria.CriteriaBuilder;
+import javax.persistence.criteria.CriteriaQuery;
+import javax.persistence.criteria.Root;
+
 import org.apache.log4j.Logger;
-import org.hibernate.Criteria;
-import org.hibernate.SQLQuery;
+import org.hibernate.Session;
 import org.hibernate.Transaction;
-import org.hibernate.classic.Session;
-import org.hibernate.criterion.Order;
-import org.hibernate.criterion.Restrictions;
+import org.hibernate.query.NativeQuery;
+import org.hibernate.query.Query;
 import org.openbravo.base.ConnectionProviderContextListener;
 import org.openbravo.base.exception.OBException;
 import org.openbravo.base.model.domaintype.BaseDomainType;
@@ -459,12 +461,17 @@
   }
 
   private <T extends ModelObject> T queryLastUpdateObject(Session session, Class<T> clazz) {
-    final Criteria c = session.createCriteria(clazz);
-    c.addOrder(Order.desc("updated"));
-    c.setMaxResults(1);
-    @SuppressWarnings("unchecked")
-    final List<T> list = c.list();
-    if (list.size() == 0) {
+    CriteriaBuilder builder = session.getCriteriaBuilder();
+    CriteriaQuery<T> criteria = builder.createQuery(clazz);
+    Root<T> root = criteria.from(clazz);
+    criteria.select(root);
+    criteria.orderBy(builder.desc(root.get("updated")));
+
+    Query<T> query = session.createQuery(criteria);
+    query.setMaxResults(1);
+
+    final List<T> list = query.list();
+    if (list.isEmpty()) {
       throw new OBException("No instances of " + clazz.getName()
           + " in the database, has the database been created and filled with data?");
     }
@@ -477,12 +484,15 @@
     tables = null;
   }
 
-  @SuppressWarnings("unchecked")
   private List<Column> readColumns(Session session) {
-    final Criteria c = session.createCriteria(Column.class);
-    c.addOrder(Order.asc("position"));
-    c.addOrder(Order.asc("name"));
-    return c.list();
+    CriteriaBuilder builder = session.getCriteriaBuilder();
+    CriteriaQuery<Column> criteria = builder.createQuery(Column.class);
+    Root<Column> root = criteria.from(Column.class);
+    criteria.select(root);
+    criteria.orderBy(builder.asc(root.get("position")), builder.asc(root.get("name")));
+
+    Query<Column> query = session.createQuery(criteria);
+    return query.list();
   }
 
   private void assignColumnsToTable(List<Column> cols) {
@@ -620,14 +630,13 @@
       SessionFactoryController sfController) {
     final String columnQry = sfController.getColumnMetadataQuery();
 
-    final Map<String, Boolean> result = new HashMap<String, Boolean>();
-    final SQLQuery sqlQuery = session.createSQLQuery(columnQry);
-    for (final Object row : sqlQuery.list()) {
+    final Map<String, Boolean> result = new HashMap<>();
+    for (final Object row : session.createNativeQuery(columnQry).list()) {
       final Object[] vals = (Object[]) row;
       final String key = createColumnMandatoryKey(vals[0], vals[1]);
       if (vals[2] instanceof String) {
         // note the string contains Y or N
-        result.put(key, ((String) vals[2]).toUpperCase().equals("N"));
+        result.put(key, ((String) vals[2]).equalsIgnoreCase("N"));
       } else {
         result.put(key, (Boolean) vals[2]);
       }
@@ -688,8 +697,9 @@
   // uniqueconstraints from the database
   private List<UniqueConstraintColumn> getUniqueConstraintColumns(Session session,
       SessionFactoryController sessionFactoryController) {
-    final List<UniqueConstraintColumn> result = new ArrayList<UniqueConstraintColumn>();
-    final SQLQuery sqlQuery = session.createSQLQuery(sessionFactoryController
+    final List<UniqueConstraintColumn> result = new ArrayList<>();
+    @SuppressWarnings("rawtypes")
+    final NativeQuery sqlQuery = session.createNativeQuery(sessionFactoryController
         .getUniqueConstraintQuery());
     for (final Object row : sqlQuery.list()) {
       // cast to an array of strings!
@@ -862,22 +872,39 @@
     }
   }
 
-  @SuppressWarnings("unchecked")
-  public <T extends Object> List<T> list(Session s, Class<T> clazz) {
-    final Criteria c = s.createCriteria(clazz);
-    return c.list();
+  /**
+   * Retrieves a list of model objects of the class passed as parameter.
+   * 
+   * @param session
+   *          the session used to query for the objects
+   * @param clazz
+   *          the class of the model objects to be retrieved
+   * @return a list of model objects
+   */
+  public <T extends Object> List<T> list(Session session, Class<T> clazz) {
+    CriteriaBuilder builder = session.getCriteriaBuilder();
+    CriteriaQuery<T> criteria = builder.createQuery(clazz);
+    Root<T> root = criteria.from(clazz);
+    criteria.select(root);
+
+    Query<T> query = session.createQuery(criteria);
+    return query.list();
   }
 
   public List<Module> getModules() {
     return modules;
   }
 
-  @SuppressWarnings("unchecked")
-  private List<Module> retrieveModules(Session s) {
-    final Criteria c = s.createCriteria(Module.class);
-    c.addOrder(Order.asc("seqno"));
-    c.add(Restrictions.eq("active", true));
-    return c.list();
+  private List<Module> retrieveModules(Session session) {
+    CriteriaBuilder builder = session.getCriteriaBuilder();
+    CriteriaQuery<Module> criteria = builder.createQuery(Module.class);
+    Root<Module> root = criteria.from(Module.class);
+    criteria.select(root);
+    criteria.where(builder.equal(root.get("active"), true));
+    criteria.orderBy(builder.asc(root.get("seqno")));
+
+    Query<Module> query = session.createQuery(criteria);
+    return query.list();
   }
 
   /**
--- a/src/org/openbravo/base/model/Property.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/base/model/Property.java	Tue Jul 24 10:44:21 2018 +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-2016 Openbravo SLU 
+ * All portions are Copyright (C) 2008-2018 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -120,7 +120,6 @@
   private String displayProperty;
 
   private Property trlParentProperty;
-  private Property trlOneToManyProperty;
 
   private Integer seqno;
   private boolean usedSequence;
@@ -1291,7 +1290,6 @@
       if (pk.equals(trlParent.getReferencedProperty())) {
         this.trlParentProperty = trlParent;
         this.translationProperty = translationProperty;
-        this.trlOneToManyProperty = trlPropertyListInBase;
         translatable = true;
         return;
       }
@@ -1308,10 +1306,6 @@
     return trlParentProperty;
   }
 
-  public Property getTrlOneToManyProperty() {
-    return trlOneToManyProperty;
-  }
-
   public boolean isStoredInSession() {
     return storedInSession;
   }
@@ -1335,7 +1329,6 @@
   public void setUsedSequence(boolean usedSequence) {
     this.usedSequence = "documentno".equalsIgnoreCase(columnName)
         || (usedSequence && "Value".equals(columnName));
-    ;
   }
 
   public String getSqlLogic() {
--- a/src/org/openbravo/base/model/domaintype/TreeDomainType.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/base/model/domaintype/TreeDomainType.java	Tue Jul 24 10:44:21 2018 +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-2014 Openbravo SLU 
+ * All portions are Copyright (C) 2013-2018 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -23,10 +23,8 @@
 import java.util.List;
 
 import org.apache.log4j.Logger;
-import org.hibernate.Criteria;
 import org.hibernate.Session;
-import org.hibernate.criterion.Order;
-import org.hibernate.criterion.Restrictions;
+import org.hibernate.query.Query;
 import org.openbravo.base.model.Column;
 import org.openbravo.base.model.ModelProvider;
 import org.openbravo.base.model.RefTree;
@@ -44,7 +42,7 @@
 
   @Override
   public List<Class<?>> getClasses() {
-    List<Class<?>> listOfClasses = new ArrayList<Class<?>>();
+    List<Class<?>> listOfClasses = new ArrayList<>();
     listOfClasses.add(RefTree.class);
     return listOfClasses;
   }
@@ -53,9 +51,12 @@
 
     Session session = ModelProvider.getInstance().getSession();
 
-    final Criteria criteria = session.createCriteria(RefTree.class);
-    criteria.add(Restrictions.eq("referenceId", getReference().getId()));
-    final List<?> list = criteria.list();
+    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());
+    final List<RefTree> list = query.list();
     if (list.isEmpty()) {
       // a base reference
       if (getReference().getParentReference() == null) {
@@ -67,7 +68,7 @@
       log.warn("Reference " + getReference()
           + " has more than one tree definition, only one is really used");
     }
-    final RefTree treeReference = (RefTree) list.get(0);
+    final RefTree treeReference = list.get(0);
     Table table = treeReference.getTable();
     if (table == null) {
       throw new IllegalStateException("The tree reference " + treeReference.getIdentifier()
@@ -84,18 +85,20 @@
     }
   }
 
-  @SuppressWarnings("unchecked")
   private Column readKeyColumn(Session session, Table table) {
-    final Criteria c = session.createCriteria(Column.class);
-    c.add(Restrictions.eq("table", table));
-    c.add(Restrictions.eq("key", true));
-    c.addOrder(Order.asc("position"));
-    Column keyColumn = null;
-    List<Column> keyColumns = c.list();
-    if (!keyColumns.isEmpty()) {
-      keyColumn = keyColumns.get(0);
+    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);
+
+    List<Column> keyColumns = query.list();
+    if (keyColumns.isEmpty()) {
+      return null;
     }
-    return keyColumn;
+    return keyColumns.get(0);
   }
 
   @Override
--- a/src/org/openbravo/base/secureApp/UserLock.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/base/secureApp/UserLock.java	Tue Jul 24 10:44:21 2018 +0200
@@ -25,8 +25,8 @@
 import java.util.concurrent.TimeUnit;
 
 import org.apache.log4j.Logger;
-import org.hibernate.Query;
 import org.hibernate.criterion.Restrictions;
+import org.hibernate.query.Query;
 import org.openbravo.base.session.OBPropertiesProvider;
 import org.openbravo.dal.core.OBContext;
 import org.openbravo.dal.service.OBCriteria;
@@ -105,9 +105,9 @@
     hql.append("  from ADSession s1");
     hql.append(" where s1.username = :name");
     hql.append("   and s1.loginStatus != 'F'");
-    Query q1 = OBDal.getInstance().getSession().createQuery(hql.toString());
+    Query<Date> q1 = OBDal.getInstance().getSession().createQuery(hql.toString(), Date.class);
     q1.setParameter("name", userName);
-    Date lastFailedAttempt = (Date) q1.list().get(0);
+    Date lastFailedAttempt = q1.list().get(0);
 
     if (lastFailedAttempt == null) {
       Calendar yesterday = Calendar.getInstance();
@@ -124,13 +124,13 @@
     hql.append("   and s.username = :name");
     hql.append("   and s.creationDate > :lastFail");
 
-    Query q = OBDal.getInstance().getSession().createQuery(hql.toString());
+    Query<Long> q = OBDal.getInstance().getSession().createQuery(hql.toString(), Long.class);
     q.setParameter("name", userName);
     q.setParameter("lastFail", lastFailedAttempt);
 
-    numberOfFails = ((Long) q.list().get(0)).intValue();
+    numberOfFails = q.list().get(0).intValue();
     log4j.debug("Time taken to check user lock " + (System.currentTimeMillis() - t)
-        + "ms. Time of 2nd query " + ((System.currentTimeMillis() - t1))
+        + "ms. Time of 2nd query " + (System.currentTimeMillis() - t1)
         + "ms. Number of failed login attempts: " + numberOfFails);
 
     if (numberOfFails == 0) {
--- a/src/org/openbravo/base/session/DalUUIDGenerator.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/base/session/DalUUIDGenerator.java	Tue Jul 24 10:44:21 2018 +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 Openbravo SLU 
+ * All portions are Copyright (C) 2011-2018 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -22,7 +22,7 @@
 import java.io.Serializable;
 
 import org.hibernate.HibernateException;
-import org.hibernate.engine.SessionImplementor;
+import org.hibernate.engine.spi.SharedSessionContractImplementor;
 import org.hibernate.id.UUIDGenerator;
 import org.openbravo.base.exception.OBException;
 import org.openbravo.base.model.BaseOBObjectDef;
@@ -42,7 +42,8 @@
 public class DalUUIDGenerator extends UUIDGenerator {
 
   @Override
-  public Serializable generate(SessionImplementor session, Object obj) throws HibernateException {
+  public Serializable generate(SharedSessionContractImplementor session, Object obj)
+      throws HibernateException {
     final BaseOBObjectDef bob = (BaseOBObjectDef) obj;
     if (bob.getId() != null) {
       return ((String) bob.getId()).toUpperCase();
--- a/src/org/openbravo/base/session/SessionFactoryController.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/base/session/SessionFactoryController.java	Tue Jul 24 10:44:21 2018 +0200
@@ -25,18 +25,18 @@
 import java.util.Map.Entry;
 import java.util.Properties;
 
-import org.apache.log4j.Logger;
 import org.hibernate.SessionFactory;
+import org.hibernate.cfg.AvailableSettings;
 import org.hibernate.cfg.Configuration;
-import org.hibernate.cfg.Environment;
-import org.hibernate.connection.ConnectionProvider;
-import org.hibernate.connection.DriverManagerConnectionProvider;
-import org.hibernate.dialect.PostgreSQLDialect;
+import org.hibernate.dialect.PostgreSQL82Dialect;
 import org.hibernate.dialect.function.SQLFunction;
-import org.hibernate.impl.SessionFactoryImpl;
+import org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl;
+import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
 import org.openbravo.base.exception.OBException;
 import org.openbravo.base.provider.OBProvider;
 import org.openbravo.dal.core.DalSessionFactory;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 /**
  * Initializes and provides the session factory to the rest of the application. There are subclasses
@@ -46,7 +46,7 @@
  */
 
 public abstract class SessionFactoryController {
-  private static final Logger log = Logger.getLogger(SessionFactoryController.class);
+  private static final Logger log = LoggerFactory.getLogger(SessionFactoryController.class);
 
   // note the order by is really important otherwise the build of
   // uniqueconstraints (ModelProvider) can fail with strange errors.
@@ -89,8 +89,7 @@
 
   public static synchronized void setInstance(SessionFactoryController sfc) {
     if (sfc != null) {
-      log.debug("Setting instance of " + sfc.getClass().getName()
-          + " as session factory controller");
+      log.debug("Setting instance of {} as session factory controller", sfc.getClass().getName());
     } else {
       log.debug("Nullifying session factory controller");
     }
@@ -146,33 +145,25 @@
     // which are actually used
     // NOTE: reads the hibernate.properties in the root of the classpath
     try {
-      configuration = new Configuration();
+      configuration = buildConfiguration();
       mapModel(configuration);
       setInterceptor(configuration);
 
       final Properties properties = getOpenbravoProperties();
-      bbddUser = properties.getProperty(Environment.USER);
+      bbddUser = properties.getProperty(AvailableSettings.USER);
       configuration.addProperties(properties);
 
       // second-level caching is disabled for now because not all data
       // access and updates go through hibernate.
       // TODO: move to configuration file
-      configuration.getProperties().setProperty(Environment.USE_SECOND_LEVEL_CACHE, "false");
-      configuration.getProperties().setProperty(Environment.USE_QUERY_CACHE, "false");
-      configuration.getProperties().setProperty(Environment.DEFAULT_BATCH_FETCH_SIZE, "50");
-      configuration.getProperties().setProperty(Environment.STATEMENT_BATCH_SIZE, "10");
-      configuration.getProperties().setProperty(Environment.STATEMENT_FETCH_SIZE, "50");
-      if (properties.containsKey(Environment.QUERY_PLAN_CACHE_MAX_STRONG_REFERENCES)) {
-        configuration.getProperties().setProperty(
-            Environment.QUERY_PLAN_CACHE_MAX_STRONG_REFERENCES,
-            properties.getProperty(Environment.QUERY_PLAN_CACHE_MAX_STRONG_REFERENCES));
-      }
-      if (properties.containsKey(Environment.QUERY_PLAN_CACHE_MAX_SOFT_REFERENCES)) {
-        configuration.getProperties().setProperty(Environment.QUERY_PLAN_CACHE_MAX_SOFT_REFERENCES,
-            properties.getProperty(Environment.QUERY_PLAN_CACHE_MAX_SOFT_REFERENCES));
-      }
-
-      configuration.getProperties().setProperty("javax.persistence.validation.mode", "NONE");
+      configuration.getProperties().setProperty(AvailableSettings.USE_SECOND_LEVEL_CACHE, "false");
+      configuration.getProperties().setProperty(AvailableSettings.USE_QUERY_CACHE, "false");
+      configuration.getProperties().setProperty(AvailableSettings.BATCH_FETCH_STYLE, "LEGACY");
+      configuration.getProperties().setProperty(AvailableSettings.DEFAULT_BATCH_FETCH_SIZE, "50");
+      configuration.getProperties().setProperty(AvailableSettings.STATEMENT_BATCH_SIZE, "10");
+      configuration.getProperties().setProperty(AvailableSettings.STATEMENT_FETCH_SIZE, "50");
+      configuration.getProperties().setProperty(AvailableSettings.JPA_VALIDATION_MODE, "NONE");
+      configuration.getProperties().setProperty(AvailableSettings.CHECK_NULLABILITY, "false");
       // TODO: consider setting isolation level explicitly
       // configuration.getProperties().setProperty(Environment.ISOLATION,
       // "" + Connection.TRANSACTION_READ_COMMITTED);
@@ -184,29 +175,34 @@
       SessionFactory delegateSessionFactory = configuration.buildSessionFactory();
       dalSessionFactory.setDelegateSessionFactory(delegateSessionFactory);
 
-      // when session factory is created, a basic Hibernate pool is also created, let's reset it to
-      // prevent leaked connections
-      if (delegateSessionFactory instanceof SessionFactoryImpl) {
-        ConnectionProvider hibernatePool = ((SessionFactoryImpl) delegateSessionFactory)
-            .getSettings().getConnectionProvider();
-        if (hibernatePool instanceof DriverManagerConnectionProvider) {
-          hibernatePool.close();
-        }
-      }
       sessionFactory = dalSessionFactory;
 
       log.debug("Session Factory initialized");
+    } catch (final OBException obex) {
+      throw obex;
     } catch (final Throwable t) {
       throw new OBException(t);
     }
   }
 
+  /**
+   * Creates the Configuration instance used to build the SessionFactory. It can be extended by the
+   * subclasses for example if they need to register a Service Provider Interface to customize the
+   * Hibernate internals.
+   * 
+   * @return a {@code Configuration} instance used to build the {@code SessionFactory}
+   */
+  protected Configuration buildConfiguration() {
+    return new Configuration();
+  }
+
   private void registerSqlFunctions() {
     Map<String, SQLFunction> sqlFunctions = getSQLFunctions();
     if (sqlFunctions == null || sqlFunctions.isEmpty()) {
       return;
     }
     for (Entry<String, SQLFunction> entry : sqlFunctions.entrySet()) {
+      log.debug("Registering SQL function: {}", entry.getKey());
       configuration.addSqlFunction(entry.getKey(), entry.getValue());
     }
   }
@@ -215,6 +211,14 @@
     return Collections.emptyMap();
   }
 
+  public void closeHibernatePool() {
+    ConnectionProvider hibernatePool = sessionFactory.getSessionFactoryOptions()
+        .getServiceRegistry().getService(ConnectionProvider.class);
+    if (hibernatePool != null && hibernatePool instanceof DriverManagerConnectionProviderImpl) {
+      ((DriverManagerConnectionProviderImpl) hibernatePool).stop();
+    }
+  }
+
   protected abstract void mapModel(Configuration theConfiguration);
 
   protected Properties getOpenbravoProperties() {
@@ -252,16 +256,16 @@
   private Properties getPostgresHbProps(Properties obProps) {
     isPostgresDatabase = true;
     final Properties props = new Properties();
-    props.setProperty(Environment.DIALECT, PostgreSQLDialect.class.getName());
+    props.setProperty(AvailableSettings.DIALECT, PostgreSQL82Dialect.class.getName());
     if (isJNDIModeOn(obProps)) {
       setJNDI(obProps, props);
     } else {
-      props.setProperty(Environment.DRIVER, "org.postgresql.Driver");
-      props.setProperty(Environment.URL,
+      props.setProperty(AvailableSettings.DRIVER, "org.postgresql.Driver");
+      props.setProperty(AvailableSettings.URL,
           obProps.getProperty("bbdd.url") + "/" + obProps.getProperty("bbdd.sid"));
 
-      props.setProperty(Environment.USER, obProps.getProperty("bbdd.user"));
-      props.setProperty(Environment.PASS, obProps.getProperty("bbdd.password"));
+      props.setProperty(AvailableSettings.USER, obProps.getProperty("bbdd.user"));
+      props.setProperty(AvailableSettings.PASS, obProps.getProperty("bbdd.password"));
     }
     return props;
   }
@@ -269,14 +273,14 @@
   private Properties getOracleHbProps(Properties obProps) {
     isPostgresDatabase = false;
     final Properties props = new Properties();
-    props.setProperty(Environment.DIALECT, OBOracle10gDialect.class.getName());
+    props.setProperty(AvailableSettings.DIALECT, OBOracle10gDialect.class.getName());
     if (isJNDIModeOn(obProps)) {
       setJNDI(obProps, props);
     } else {
-      props.setProperty(Environment.DRIVER, "oracle.jdbc.driver.OracleDriver");
-      props.setProperty(Environment.URL, obProps.getProperty("bbdd.url"));
-      props.setProperty(Environment.USER, obProps.getProperty("bbdd.user"));
-      props.setProperty(Environment.PASS, obProps.getProperty("bbdd.password"));
+      props.setProperty(AvailableSettings.DRIVER, "oracle.jdbc.driver.OracleDriver");
+      props.setProperty(AvailableSettings.URL, obProps.getProperty("bbdd.url"));
+      props.setProperty(AvailableSettings.USER, obProps.getProperty("bbdd.user"));
+      props.setProperty(AvailableSettings.PASS, obProps.getProperty("bbdd.password"));
     }
     return props;
   }
@@ -284,21 +288,21 @@
   private Properties getDB2HbProps(Properties obProps) {
     isPostgresDatabase = false;
     final Properties props = new Properties();
-    props.setProperty(Environment.DIALECT, OBDB2v97Dialect.class.getName());
+    props.setProperty(AvailableSettings.DIALECT, OBDB2v97Dialect.class.getName());
     if (isJNDIModeOn(obProps)) {
       setJNDI(obProps, props);
     } else {
-      props.setProperty(Environment.DRIVER, "com.ibm.db2.jcc.DB2Driver");
-      props.setProperty(Environment.URL, obProps.getProperty("bbdd.url"));
-      props.setProperty(Environment.USER, obProps.getProperty("bbdd.user"));
-      props.setProperty(Environment.PASS, obProps.getProperty("bbdd.password"));
+      props.setProperty(AvailableSettings.DRIVER, "com.ibm.db2.jcc.DB2Driver");
+      props.setProperty(AvailableSettings.URL, obProps.getProperty("bbdd.url"));
+      props.setProperty(AvailableSettings.USER, obProps.getProperty("bbdd.user"));
+      props.setProperty(AvailableSettings.PASS, obProps.getProperty("bbdd.password"));
     }
     return props;
   }
 
   private void setJNDI(Properties obProps, Properties hbProps) {
-    log.info("Using JNDI with resource name-> " + obProps.getProperty("JNDI.resourceName"));
-    hbProps.setProperty(Environment.DATASOURCE,
+    log.info("Using JNDI with resource name-> {}", obProps.getProperty("JNDI.resourceName"));
+    hbProps.setProperty(AvailableSettings.DATASOURCE,
         "java:/comp/env/" + obProps.getProperty("JNDI.resourceName"));
   }
 
--- a/src/org/openbravo/base/structure/BaseOBObject.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/base/structure/BaseOBObject.java	Tue Jul 24 10:44:21 2018 +0200
@@ -20,9 +20,8 @@
 package org.openbravo.base.structure;
 
 import java.io.Serializable;
-import java.util.List;
 
-import org.hibernate.criterion.Restrictions;
+import org.hibernate.query.Query;
 import org.openbravo.base.exception.OBSecurityException;
 import org.openbravo.base.model.BaseOBObjectDef;
 import org.openbravo.base.model.Entity;
@@ -34,7 +33,6 @@
 import org.openbravo.base.validation.ValidationException;
 import org.openbravo.dal.core.OBContext;
 import org.openbravo.dal.core.OBInterceptor;
-import org.openbravo.dal.service.OBCriteria;
 import org.openbravo.dal.service.OBDal;
 import org.openbravo.model.ad.system.Language;
 
@@ -126,42 +124,16 @@
     if (p.isTranslatable() && OBContext.hasTranslationInstalled()) {
       if (!hasLookedForTrl) {
         hasLookedForTrl = true;
-        OBContext.setAdminMode(true);
         try {
-          @SuppressWarnings("unchecked")
-          List<BaseOBObject> trl = OBDal
-              .getInstance()
-              .getSession()
-              .createFilter(this.get(p.getTrlOneToManyProperty().getName()),
-                  "where language = :language").setParameter("language", language).list();
-
-          if (!trl.isEmpty()) {
-            dataTrl = trl.get(0);
+          if (id != null && p.getTrlParentProperty() != null) {
+            BaseOBObject translation = getTranslation(p.getTrlParentProperty(), language, id);
+            if (translation != null) {
+              dataTrl = translation;
+            }
           }
         } catch (Throwable t) {
-          // Log error but do not fail here
-          log.debug("Error looking for translation of " + p + " in Session. Looking in Object.", t);
-
-          try {
-            if (id != null) {
-              if (p.getTrlParentProperty() != null) {
-                // check whether translation is available in the object and not stored in session
-                OBCriteria<BaseOBObject> trlList = OBDal.getInstance().createCriteria(
-                    p.getEntity().getName() + "Trl");
-                trlList.add(Restrictions.eq(p.getTrlParentProperty().getName(), OBDal.getInstance()
-                    .get(p.getEntity().toString(), id)));
-                trlList.add(Restrictions.eq("language", language));
-                if (trlList.count() > 0) {
-                  dataTrl = trlList.list().get(0);
-                }
-              }
-            }
-          } catch (Throwable t1) {
-            // continue using base language
-            log.debug("Error looking for translation of " + p + ". Using base value", t);
-          }
-        } finally {
-          OBContext.restorePreviousMode();
+          // continue using base language
+          log.debug("Error looking for translation of " + p + ". Using base value", t);
         }
       }
 
@@ -173,6 +145,19 @@
     return data[p.getIndexInEntity()];
   }
 
+  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");
+    Query<BaseOBObject> query = OBDal.getInstance().getSession()
+        .createQuery(hql.toString(), BaseOBObject.class);
+    query.setParameter("id", id);
+    query.setParameter("language", language);
+    query.setMaxResults(1);
+    return query.uniqueResult();
+  }
+
   private void setDataValue(String propName, Object value) {
     if (data == null) {
       data = new Object[getEntity().getProperties().size()];
--- a/src/org/openbravo/cluster/ClusterServiceManager.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/cluster/ClusterServiceManager.java	Tue Jul 24 10:44:21 2018 +0200
@@ -29,7 +29,6 @@
 import javax.inject.Inject;
 
 import org.apache.commons.lang.StringUtils;
-import org.hibernate.Query;
 import org.hibernate.criterion.Restrictions;
 import org.openbravo.base.ConfigParameters;
 import org.openbravo.base.provider.OBProvider;
@@ -362,13 +361,13 @@
       hql.append("UPDATE ADClusterService ");
       hql.append("SET nodeID = :newNodeId, nodeName = :newNodeName, updated = :updated ");
       hql.append("WHERE service = :service AND nodeID = :formerNodeId");
-      Query updateQuery = OBDal.getInstance().getSession().createQuery(hql.toString());
-      updateQuery.setParameter("newNodeId", manager.nodeId);
-      updateQuery.setParameter("newNodeName", manager.nodeName);
-      updateQuery.setParameter("updated", now);
-      updateQuery.setParameter("service", serviceName);
-      updateQuery.setParameter("formerNodeId", formerNodeId);
-      int rowCount = updateQuery.executeUpdate();
+      int rowCount = OBDal.getInstance().getSession().createQuery(hql.toString()) //
+          .setParameter("newNodeId", manager.nodeId) //
+          .setParameter("newNodeName", manager.nodeName) //
+          .setParameter("updated", now) //
+          .setParameter("service", serviceName) //
+          .setParameter("formerNodeId", formerNodeId) //
+          .executeUpdate();
       if (rowCount == 1) {
         String replaceMsg = "Replaced node {} with node {} in charge of service " + serviceName;
         log.info(replaceMsg, formerNodeId, getNodeIdentifier());
@@ -379,11 +378,11 @@
       StringBuilder hql = new StringBuilder();
       hql.append("UPDATE ADClusterService SET updated = :updated ");
       hql.append("WHERE service = :service AND nodeID = :currentNodeId");
-      Query updateQuery = OBDal.getInstance().getSession().createQuery(hql.toString());
-      updateQuery.setParameter("updated", now);
-      updateQuery.setParameter("service", serviceName);
-      updateQuery.setParameter("currentNodeId", manager.nodeId);
-      updateQuery.executeUpdate();
+      OBDal.getInstance().getSession().createQuery(hql.toString()) //
+          .setParameter("updated", now) //
+          .setParameter("service", serviceName) //
+          .setParameter("currentNodeId", manager.nodeId) //
+          .executeUpdate();
     }
 
     private String getNodeIdentifier() {
--- a/src/org/openbravo/common/datasource/CostingTransactionsHQLTransformer.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/common/datasource/CostingTransactionsHQLTransformer.java	Tue Jul 24 10:44:21 2018 +0200
@@ -23,7 +23,7 @@
 import java.util.Map;
 import java.util.Set;
 
-import org.hibernate.Query;
+import org.hibernate.query.Query;
 import org.openbravo.base.structure.BaseOBObject;
 import org.openbravo.client.kernel.ComponentProvider;
 import org.openbravo.costing.CostAdjustmentUtils;
@@ -171,7 +171,8 @@
         + Costing.PROPERTY_ENDINGDATE + " desc, trx."
         + MaterialTransaction.PROPERTY_MOVEMENTQUANTITY);
 
-    Query prevCostingQuery = OBDal.getInstance().getSession().createQuery(query.toString());
+    Query<String> prevCostingQuery = OBDal.getInstance().getSession()
+        .createQuery(query.toString(), String.class);
     prevCostingQuery.setParameter("productId", transaction.getProduct().getId());
     prevCostingQuery.setParameter("refid", MOVEMENTTYPE_REF_ID);
     prevCostingQuery.setParameter("movementDate", transaction.getMovementDate());
@@ -188,7 +189,6 @@
     prevCostingQuery.setParameter("clientId", transaction.getClient().getId());
     prevCostingQuery.setMaxResults(1);
 
-    @SuppressWarnings("unchecked")
     final List<String> preCostingIdList = prevCostingQuery.list();
 
     Costing prevCosting = null;
--- a/src/org/openbravo/common/datasource/StockReservationPickAndEditDataSource.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/common/datasource/StockReservationPickAndEditDataSource.java	Tue Jul 24 10:44:21 2018 +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) 2014-2017 Openbravo SLU
+ * All portions are Copyright (C) 2014-2018 Openbravo SLU
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -34,11 +34,11 @@
 import org.codehaus.jettison.json.JSONArray;
 import org.codehaus.jettison.json.JSONException;
 import org.codehaus.jettison.json.JSONObject;
-import org.hibernate.Query;
 import org.hibernate.Session;
 import org.hibernate.criterion.Criterion;
 import org.hibernate.criterion.Order;
 import org.hibernate.criterion.Restrictions;
+import org.hibernate.query.Query;
 import org.openbravo.base.exception.OBSecurityException;
 import org.openbravo.base.model.Entity;
 import org.openbravo.base.model.ModelProvider;
@@ -1013,7 +1013,8 @@
     hqlString.append(" order by rs.salesOrderLine DESC, r.warehouse, sb");
 
     final Session session = OBDal.getInstance().getSession();
-    Query query = session.createQuery(hqlString.toString());
+    Query<ReservationStock> query = session.createQuery(hqlString.toString(),
+        ReservationStock.class);
     query.setParameter("reservation", reservation);
 
     if (reservation.getAttributeSetValue() != null) {
@@ -1041,13 +1042,12 @@
       query.setParameterList("inventoryStatusFiltered", inventoryStatusFiltered);
     }
 
-    for (Object o : query.list()) {
+    for (ReservationStock rs : query.list()) {
       Map<String, Object> myMap = new HashMap<String, Object>();
-      ReservationStock rs = (ReservationStock) o;
       if (selectedIds.size() > 0) {
         for (int i = 0; i < selectedIds.size(); i++) {
           if (!(rs.getId().equals(selectedIds.get(i)))) {
-            // Check Filter Criterias
+            // Check Filter Criteria
             if (availableQtyFilterCriteria != null
                 && !"".equals(availableQtyFilterCriteria)
                 && !isInScope(
@@ -1154,13 +1154,14 @@
     hqlString.append(" order by rs.salesOrderLine DESC, r.warehouse, rs.storageBin");
 
     final Session session = OBDal.getInstance().getSession();
-    Query query = session.createQuery(hqlString.toString());
+    Query<ReservationStock> query = session.createQuery(hqlString.toString(),
+        ReservationStock.class);
     query.setParameter("reservation", reservation);
     query.setParameter("storageBin", sb);
     query.setParameter("attributeSetValue", as);
     query.setMaxResults(1);
 
-    rs = !query.list().isEmpty() ? (ReservationStock) query.list().get(0) : null;
+    rs = !query.list().isEmpty() ? query.list().get(0) : null;
     return rs;
   }
 
@@ -1176,7 +1177,7 @@
     hqlString.append("join  ol.salesOrder as o ");
     hqlString.append("where o.salesTransaction = false and o.documentStatus = 'CO' ");
     hqlString.append("and ol.product = :product ");
-    // Organization filter not required as on hand warehouses is sufficent
+    // Organization filter not required as on hand warehouses is sufficient
     // hqlString.append("and ol.organization.id in :organizations ");
     hqlString.append("and o.warehouse in :warehouses ");
 
@@ -1215,7 +1216,7 @@
         .append("and ol.orderedQuantity <> coalesce((select Sum(mpo.quantity) from ProcurementPOInvoiceMatch as mpo where mpo.salesOrderLine = ol and mpo.goodsShipmentLine is not null),0)");
     hqlString.append("order by o.documentNo, ol.lineNo");
     final Session session = OBDal.getInstance().getSession();
-    Query query = session.createQuery(hqlString.toString());
+    Query<OrderLine> query = session.createQuery(hqlString.toString(), OrderLine.class);
     query.setParameter("product", reservation.getProduct());
     query.setParameter("reservation", reservation);
     // query.setParameterList("organizations", organizations);
@@ -1232,9 +1233,8 @@
     if (orderLinesFiltered != null && orderLinesFiltered.size() > 0) {
       query.setParameterList("orderLinesFiltered", orderLinesFiltered);
     }
-    for (Object o : query.list()) {
+    for (OrderLine orderLine : query.list()) {
       Map<String, Object> myMap = new HashMap<String, Object>();
-      OrderLine orderLine = (OrderLine) o;
       myMap.put("id", orderLine.getId());
       myMap.put("obSelected", false);
       myMap.put("reservationStock", null);
@@ -1358,7 +1358,7 @@
     hqlString.append("sd.storageBin.levelZ, sd.attributeSetValue.description");
 
     final Session session = OBDal.getInstance().getSession();
-    Query query = session.createQuery(hqlString.toString());
+    Query<StorageDetail> query = session.createQuery(hqlString.toString(), StorageDetail.class);
     query.setParameter("product", reservation.getProduct());
     query.setParameter("uom", reservation.getUOM());
 
@@ -1399,12 +1399,11 @@
       }
     }
 
-    for (Object o : query.list()) {
-      StorageDetail sd = (StorageDetail) o;
+    for (StorageDetail sd : query.list()) {
       if (selectedIds.size() > 0) {
         for (int i = 0; i < selectedIds.size(); i++) {
           if (!(sd.getId().equals(selectedIds.get(i)))) {
-            // Check Filter Criterias
+            // Check Filter Criteria
             if (availableQtyFilterCriteria != null && !"".equals(availableQtyFilterCriteria)
                 && !isInScope("availableQty", availableQtyFilterCriteria, sd.getQuantityOnHand())) {
               continue;
@@ -1692,7 +1691,7 @@
       hqlString.append(" and sd.attributeSetValue = :attributeSetValue ");
     }
     final Session session = OBDal.getInstance().getSession();
-    Query query = session.createQuery(hqlString.toString());
+    Query<BigDecimal> query = session.createQuery(hqlString.toString(), BigDecimal.class);
     query.setParameter("product", product);
     if (storageBin != null) {
       query.setParameter("storageBin", storageBin);
@@ -1700,7 +1699,7 @@
     if (attribute != null) {
       query.setParameter("attributeSetValue", attribute);
     }
-    return (BigDecimal) query.uniqueResult();
+    return query.uniqueResult();
   }
 
   private BigDecimal getQtyOnHandFromOrderLine(OrderLine orderline) {
@@ -1728,10 +1727,10 @@
     hqlString.append(" and rs.salesOrderLine = :orderLine ");
     hqlString.append(" and r <> :reservation ");
     final Session session = OBDal.getInstance().getSession();
-    Query query = session.createQuery(hqlString.toString());
+    Query<BigDecimal> query = session.createQuery(hqlString.toString(), BigDecimal.class);
     query.setParameter("orderLine", orderLine);
     query.setParameter("reservation", reservation);
-    return (BigDecimal) query.uniqueResult();
+    return query.uniqueResult();
   }
 
   private BigDecimal getQtyReserved(Reservation reservation, Product product,
@@ -1751,7 +1750,7 @@
       hqlString.append(" and rs.storageBin = :storageBin ");
     }
     final Session session = OBDal.getInstance().getSession();
-    Query query = session.createQuery(hqlString.toString());
+    Query<BigDecimal> query = session.createQuery(hqlString.toString(), BigDecimal.class);
     query.setParameter("product", product);
     query.setParameter("reservation", reservation);
     if (attribute != null && !"0".equals(attribute.getId())) {
@@ -1760,7 +1759,7 @@
     if (storageBin != null) {
       query.setParameter("storageBin", storageBin);
     }
-    return (BigDecimal) query.uniqueResult();
+    return query.uniqueResult();
   }
 
   private Map<String, String> buildCriteria(Map<String, String> parameters) {
--- a/src/org/openbravo/costing/CostAdjustmentProcess.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/costing/CostAdjustmentProcess.java	Tue Jul 24 10:44:21 2018 +0200
@@ -29,11 +29,11 @@
 
 import org.codehaus.jettison.json.JSONException;
 import org.codehaus.jettison.json.JSONObject;
-import org.hibernate.Query;
 import org.hibernate.ScrollMode;
 import org.hibernate.ScrollableResults;
 import org.hibernate.criterion.Order;
 import org.hibernate.criterion.Restrictions;
+import org.hibernate.query.Query;
 import org.openbravo.base.exception.OBException;
 import org.openbravo.base.provider.OBProvider;
 import org.openbravo.base.weld.WeldUtils;
@@ -108,9 +108,10 @@
     query.append(" where " + CostAdjustmentLine.PROPERTY_COSTADJUSTMENT + " = :ca");
     query.append("   and " + CostAdjustmentLine.PROPERTY_ISSOURCE + " = true");
 
-    Query qryMinDate = OBDal.getInstance().getSession().createQuery(query.toString());
+    Query<Date> qryMinDate = OBDal.getInstance().getSession()
+        .createQuery(query.toString(), Date.class);
     qryMinDate.setParameter("ca", costAdjustment);
-    Date minDate = (Date) qryMinDate.uniqueResult();
+    Date minDate = qryMinDate.uniqueResult();
     try {
       Date maxDate = CostingUtils.getMaxTransactionDate(costAdjustment.getOrganization());
       Period periodClosed = CostingUtils.periodClosed(costAdjustment.getOrganization(), minDate,
@@ -207,9 +208,10 @@
     updateQuery.append(".id = :adjustmentId and ");
     updateQuery.append(CostAdjustmentLine.PROPERTY_ISRELATEDTRANSACTIONADJUSTED);
     updateQuery.append(" = true ");
+    @SuppressWarnings("rawtypes")
     Query adjustmentLineQuery = OBDal.getInstance().getSession()
         .createQuery(updateQuery.toString());
-    adjustmentLineQuery.setString("adjustmentId", costAdjustment.getId());
+    adjustmentLineQuery.setParameter("adjustmentId", costAdjustment.getId());
     adjustmentLineQuery.executeUpdate();
   }
 
--- a/src/org/openbravo/costing/CostAdjustmentUtils.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/costing/CostAdjustmentUtils.java	Tue Jul 24 10:44:21 2018 +0200
@@ -27,10 +27,10 @@
 
 import org.apache.commons.lang.StringUtils;
 import org.apache.commons.lang.time.DateUtils;
-import org.hibernate.Query;
 import org.hibernate.ScrollMode;
 import org.hibernate.ScrollableResults;
 import org.hibernate.criterion.Restrictions;
+import org.hibernate.query.Query;
 import org.openbravo.advpaymentmngt.utility.FIN_Utility;
 import org.openbravo.base.exception.OBException;
 import org.openbravo.base.provider.OBProvider;
@@ -274,7 +274,8 @@
     where.append(" , trxtype." + propADListPriority + " desc");
     where.append(" , trx." + MaterialTransaction.PROPERTY_MOVEMENTQUANTITY + " asc");
     where.append(" , trx." + MaterialTransaction.PROPERTY_ID + " desc");
-    Query trxQry = OBDal.getInstance().getSession().createQuery(where.toString());
+    Query<String> trxQry = OBDal.getInstance().getSession()
+        .createQuery(where.toString(), String.class);
     trxQry.setParameter("refId", CostAdjustmentUtils.MovementTypeRefID);
     trxQry.setParameter("productId", trx.getProduct().getId());
     trxQry.setParameterList("orgIds", orgs);
@@ -282,7 +283,7 @@
       trxQry.setParameter("warehouseId", trx.getStorageBin().getWarehouse().getId());
     }
     trxQry.setMaxResults(1);
-    String transactionId = (String) trxQry.uniqueResult();
+    String transactionId = trxQry.uniqueResult();
 
     TransactionLast lastTransaction = null;
     if (transactionId != null) {
@@ -309,11 +310,11 @@
     where.append(" from " + CostAdjustmentLine.ENTITY_NAME + " as cal");
     where.append(" where cal." + CostAdjustmentLine.PROPERTY_COSTADJUSTMENT
         + ".id = :costAdjustment");
-    Query calQry = OBDal.getInstance().getSession().createQuery(where.toString());
+    Query<Long> calQry = OBDal.getInstance().getSession().createQuery(where.toString(), Long.class);
     calQry.setParameter("costAdjustment", cadj.getId());
     calQry.setMaxResults(1);
 
-    Long lineNo = (Long) calQry.uniqueResult();
+    Long lineNo = calQry.uniqueResult();
     if (lineNo != null) {
       return lineNo + 10L;
     }
@@ -341,7 +342,8 @@
     select.append(" group by tc." + TransactionCost.PROPERTY_CURRENCY);
     select.append(" , tc." + TransactionCost.PROPERTY_COSTDATE);
 
-    Query qry = OBDal.getInstance().getSession().createQuery(select.toString());
+    Query<Object[]> qry = OBDal.getInstance().getSession()
+        .createQuery(select.toString(), Object[].class);
     qry.setParameter("trxId", trx.getId());
     ScrollableResults scroll = qry.scroll(ScrollMode.FORWARD_ONLY);
 
@@ -398,14 +400,15 @@
     }
     subSelect.append("   and trx." + MaterialTransaction.PROPERTY_ORGANIZATION + ".id in (:orgs)");
 
-    Query trxsubQry = OBDal.getInstance().getSession().createQuery(subSelect.toString());
+    Query<Date> trxsubQry = OBDal.getInstance().getSession()
+        .createQuery(subSelect.toString(), Date.class);
     trxsubQry.setParameter("date", date);
     trxsubQry.setParameter("product", product.getId());
     if (costDimensions.get(CostDimension.Warehouse) != null) {
       trxsubQry.setParameter("warehouse", costDimensions.get(CostDimension.Warehouse).getId());
     }
     trxsubQry.setParameterList("orgs", orgs);
-    Object trxprocessDate = trxsubQry.uniqueResult();
+    Date trxprocessDate = trxsubQry.uniqueResult();
 
     StringBuffer select = new StringBuffer();
     select
@@ -422,8 +425,8 @@
     }
 
     if (trxprocessDate != null
-        && (!backdatedTransactionsFixed || ((Date) trxprocessDate).before(backdatedTrxFrom))) {
-      date = (Date) trxprocessDate;
+        && (!backdatedTransactionsFixed || trxprocessDate.before(backdatedTrxFrom))) {
+      date = trxprocessDate;
       select.append(" left join trx." + MaterialTransaction.PROPERTY_PHYSICALINVENTORYLINE
           + " as il");
       select.append(" left join il." + InventoryCountLine.PROPERTY_PHYSINVENTORY + " as i");
@@ -441,18 +444,16 @@
       select.append("  and locator." + Locator.PROPERTY_WAREHOUSE + ".id = :warehouse");
     }
     select.append("   and trx." + MaterialTransaction.PROPERTY_ORGANIZATION + ".id in (:orgs)");
-    Query trxQry = OBDal.getInstance().getSession().createQuery(select.toString());
+    Query<BigDecimal> trxQry = OBDal.getInstance().getSession()
+        .createQuery(select.toString(), BigDecimal.class);
     trxQry.setParameter("product", product.getId());
     trxQry.setParameter("date", date);
     if (costDimensions.get(CostDimension.Warehouse) != null) {
       trxQry.setParameter("warehouse", costDimensions.get(CostDimension.Warehouse).getId());
     }
     trxQry.setParameterList("orgs", orgs);
-    Object stock = trxQry.uniqueResult();
-    if (stock != null) {
-      return (BigDecimal) stock;
-    }
-    return BigDecimal.ZERO;
+    BigDecimal stock = trxQry.uniqueResult();
+    return (stock != null) ? stock : BigDecimal.ZERO;
   }
 
   /**
@@ -619,7 +620,8 @@
 
     select.append("   and trx." + MaterialTransaction.PROPERTY_ORGANIZATION + ".id in (:orgs)");
 
-    Query trxQry = OBDal.getInstance().getSession().createQuery(select.toString());
+    Query<BigDecimal> trxQry = OBDal.getInstance().getSession()
+        .createQuery(select.toString(), BigDecimal.class);
     trxQry.setParameter("refid", MovementTypeRefID);
     trxQry.setParameter("product", trx.getProduct());
     trxQry.setParameter("trxdate", trx.getTransactionProcessDate());
@@ -647,7 +649,7 @@
       trxQry.setParameter("warehouse", costDimensions.get(CostDimension.Warehouse).getId());
     }
 
-    BigDecimal stock = (BigDecimal) trxQry.uniqueResult();
+    BigDecimal stock = trxQry.uniqueResult();
     if (stock == null) {
       stock = BigDecimal.ZERO;
     }
@@ -710,14 +712,15 @@
     }
     subSelect.append("   and trx." + MaterialTransaction.PROPERTY_ORGANIZATION + ".id in (:orgs)");
 
-    Query trxsubQry = OBDal.getInstance().getSession().createQuery(subSelect.toString());
+    Query<Date> trxsubQry = OBDal.getInstance().getSession()
+        .createQuery(subSelect.toString(), Date.class);
     trxsubQry.setParameter("date", date);
     trxsubQry.setParameter("product", product.getId());
     if (costDimensions.get(CostDimension.Warehouse) != null) {
       trxsubQry.setParameter("warehouse", costDimensions.get(CostDimension.Warehouse).getId());
     }
     trxsubQry.setParameterList("orgs", orgs);
-    Object trxprocessDate = trxsubQry.uniqueResult();
+    Date trxprocessDate = trxsubQry.uniqueResult();
 
     StringBuffer select = new StringBuffer();
     select.append(" select sum(case");
@@ -741,8 +744,8 @@
     }
 
     if (trxprocessDate != null
-        && (!backdatedTransactionsFixed || ((Date) trxprocessDate).before(backdatedTrxFrom))) {
-      date = (Date) trxprocessDate;
+        && (!backdatedTransactionsFixed || trxprocessDate.before(backdatedTrxFrom))) {
+      date = trxprocessDate;
       select.append(" left join trx." + MaterialTransaction.PROPERTY_PHYSICALINVENTORYLINE
           + " as il");
       select.append(" left join il." + InventoryCountLine.PROPERTY_PHYSINVENTORY + " as i");
@@ -771,7 +774,8 @@
     select.append(" group by tc." + TransactionCost.PROPERTY_CURRENCY);
     select.append("   , tc." + TransactionCost.PROPERTY_ACCOUNTINGDATE);
 
-    Query trxQry = OBDal.getInstance().getSession().createQuery(select.toString());
+    Query<Object[]> trxQry = OBDal.getInstance().getSession()
+        .createQuery(select.toString(), Object[].class);
     trxQry.setParameter("product", product);
     trxQry.setParameter("date", date);
     if (costDimensions.get(CostDimension.Warehouse) != null) {
@@ -986,7 +990,8 @@
     select.append(" group by tc." + TransactionCost.PROPERTY_CURRENCY);
     select.append("   , tc." + TransactionCost.PROPERTY_ACCOUNTINGDATE);
 
-    Query trxQry = OBDal.getInstance().getSession().createQuery(select.toString());
+    Query<Object[]> trxQry = OBDal.getInstance().getSession()
+        .createQuery(select.toString(), Object[].class);
     trxQry.setParameter("refid", MovementTypeRefID);
     trxQry.setParameter("product", trx.getProduct());
     trxQry.setParameter("trxdate", trx.getTransactionProcessDate());
@@ -1069,21 +1074,21 @@
     if (wh != null) {
       select.append("   and loc." + Locator.PROPERTY_WAREHOUSE + " = :warehouse");
     }
-    Query qryMinDate = OBDal.getInstance().getSession().createQuery(select.toString());
+    Query<Date> qryMinDate = OBDal.getInstance().getSession()
+        .createQuery(select.toString(), Date.class);
     qryMinDate.setParameterList("orgs", orgs);
     qryMinDate.setParameter("product", product);
     qryMinDate.setParameter("mvntdate", refDate);
     if (wh != null) {
       qryMinDate.setParameter("warehouse", wh);
     }
-    Object objMinDate = qryMinDate.uniqueResult();
-    if (objMinDate == null) {
+    Date minNextDate = qryMinDate.uniqueResult();
+    if (minNextDate == null) {
       return null;
     }
 
     // Get the last transaction process date of transactions with movement date equal or before the
     // given date and a transaction process date before the previously calculated min date.
-    Date minNextDate = (Date) objMinDate;
     select = new StringBuffer();
     select.append(" select max(trx." + MaterialTransaction.PROPERTY_TRANSACTIONPROCESSDATE
         + ") as date");
@@ -1100,7 +1105,8 @@
     if (wh != null) {
       select.append("   and loc." + Locator.PROPERTY_WAREHOUSE + " = :warehouse");
     }
-    Query qryMaxDate = OBDal.getInstance().getSession().createQuery(select.toString());
+    Query<Date> qryMaxDate = OBDal.getInstance().getSession()
+        .createQuery(select.toString(), Date.class);
     qryMaxDate.setParameterList("orgs", orgs);
     qryMaxDate.setParameter("product", product);
     qryMaxDate.setParameter("mvntdate", refDate);
@@ -1109,12 +1115,7 @@
       qryMaxDate.setParameter("warehouse", wh);
     }
 
-    Object objMaxDate = qryMaxDate.uniqueResult();
-    if (objMaxDate == null) {
-      return null;
-    }
-
-    return (Date) objMaxDate;
+    return qryMaxDate.uniqueResult();
   }
 
   /**
--- a/src/org/openbravo/costing/CostingAlgorithmAdjustmentImp.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/costing/CostingAlgorithmAdjustmentImp.java	Tue Jul 24 10:44:21 2018 +0200
@@ -26,10 +26,10 @@
 
 import javax.enterprise.context.Dependent;
 
-import org.hibernate.Query;
 import org.hibernate.ScrollMode;
 import org.hibernate.ScrollableResults;
 import org.hibernate.criterion.Restrictions;
+import org.hibernate.query.Query;
 import org.openbravo.base.structure.BaseOBObject;
 import org.openbravo.costing.CostingAlgorithm.CostDimension;
 import org.openbravo.costing.CostingServer.TrxType;
@@ -248,11 +248,12 @@
       where.append(" from " + CostAdjustmentLine.ENTITY_NAME + " as cal");
       where.append(" where cal." + CostAdjustmentLine.PROPERTY_COSTADJUSTMENT
           + ".id = :costAdjustment");
-      Query calQry = OBDal.getInstance().getSession().createQuery(where.toString());
+      Query<Long> calQry = OBDal.getInstance().getSession()
+          .createQuery(where.toString(), Long.class);
       calQry.setParameter("costAdjustment", strCostAdjId);
       calQry.setMaxResults(1);
 
-      nextLineNo = (Long) calQry.uniqueResult();
+      nextLineNo = calQry.uniqueResult();
     }
     nextLineNo += 10L;
     return nextLineNo;
--- a/src/org/openbravo/costing/CostingBackground.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/costing/CostingBackground.java	Tue Jul 24 10:44:21 2018 +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) 2012-2017 Openbravo SLU
+ * All portions are Copyright (C) 2012-2018 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  *************************************************************************
@@ -25,7 +25,7 @@
 import javax.servlet.ServletException;
 
 import org.apache.log4j.Logger;
-import org.hibernate.Query;
+import org.hibernate.query.Query;
 import org.openbravo.base.exception.OBException;
 import org.openbravo.base.provider.OBProvider;
 import org.openbravo.dal.core.OBContext;
@@ -199,6 +199,7 @@
     hqlTransactions.append("   and trx." + MaterialTransaction.PROPERTY_COSTINGSTATUS + " <> 'S'");
     hqlTransactions.append("   and trx." + MaterialTransaction.PROPERTY_ORGANIZATION
         + ".id in (:orgs)");
+    @SuppressWarnings("rawtypes")
     Query updateTransactions = OBDal.getInstance().getSession()
         .createQuery(hqlTransactions.toString());
     updateTransactions.setParameterList("orgs", orgsWithRule);
@@ -207,7 +208,6 @@
     OBDal.getInstance().flush();
   }
 
-  @SuppressWarnings("unchecked")
   private List<String> getTransactionsBatch(List<String> orgsWithRule) {
     StringBuffer where = new StringBuffer();
     where.append(" select trx." + MaterialTransaction.PROPERTY_ID + " as id ");
@@ -227,7 +227,8 @@
     where.append(" , trxtype." + CostAdjustmentUtils.propADListPriority);
     where.append(" , trx." + MaterialTransaction.PROPERTY_MOVEMENTQUANTITY + " desc");
     where.append(" , trx." + MaterialTransaction.PROPERTY_ID);
-    Query trxQry = OBDal.getInstance().getSession().createQuery(where.toString());
+    Query<String> trxQry = OBDal.getInstance().getSession()
+        .createQuery(where.toString(), String.class);
 
     trxQry.setParameter("refid", CostAdjustmentUtils.MovementTypeRefID);
     trxQry.setParameter("now", new Date());
@@ -251,13 +252,13 @@
         + MaterialTransaction.PROPERTY_MOVEMENTTYPE);
     where.append("   and trx." + MaterialTransaction.PROPERTY_TRANSACTIONPROCESSDATE + " <= :now");
     where.append("   and trx." + MaterialTransaction.PROPERTY_ORGANIZATION + ".id in (:orgs)");
-    Query trxQry = OBDal.getInstance().getSession().createQuery(where.toString());
+    Query<Long> trxQry = OBDal.getInstance().getSession().createQuery(where.toString(), Long.class);
 
     trxQry.setParameter("refid", CostAdjustmentUtils.MovementTypeRefID);
     trxQry.setParameter("now", new Date());
     trxQry.setParameterList("orgs", orgsWithRule);
     trxQry.setMaxResults(1);
-    return ((Long) trxQry.uniqueResult()).intValue();
+    return (trxQry.uniqueResult()).intValue();
   }
 
   private void initializeMtransCostDateAcct() throws Exception {
--- a/src/org/openbravo/costing/CostingMigrationProcess.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/costing/CostingMigrationProcess.java	Tue Jul 24 10:44:21 2018 +0200
@@ -31,11 +31,11 @@
 import org.apache.commons.lang.StringUtils;
 import org.apache.commons.lang.time.DateUtils;
 import org.apache.log4j.Logger;
-import org.hibernate.Query;
-import org.hibernate.SQLQuery;
 import org.hibernate.ScrollMode;
 import org.hibernate.ScrollableResults;
 import org.hibernate.criterion.Restrictions;
+import org.hibernate.query.NativeQuery;
+import org.hibernate.query.Query;
 import org.hibernate.type.DateType;
 import org.hibernate.type.StringType;
 import org.openbravo.base.exception.OBException;
@@ -221,14 +221,16 @@
     StringBuffer delete = new StringBuffer();
     delete.append("delete from " + Alert.ENTITY_NAME);
     delete.append(" where " + Alert.PROPERTY_ALERTRULE + " = :alertRule ");
+    @SuppressWarnings("rawtypes")
     Query queryDelete = OBDal.getInstance().getSession().createQuery(delete.toString());
-    queryDelete.setEntity("alertRule", legacyCostAvailableAlert);
+    queryDelete.setParameter("alertRule", legacyCostAvailableAlert);
     queryDelete.executeUpdate();
 
     if (legacyCostAvailableAlert.isActive()) {
 
-      SQLQuery alertQry = OBDal.getInstance().getSession()
-          .createSQLQuery(legacyCostAvailableAlert.getSql());
+      @SuppressWarnings("rawtypes")
+      NativeQuery alertQry = OBDal.getInstance().getSession()
+          .createNativeQuery(legacyCostAvailableAlert.getSql());
       alertQry.addScalar("REFERENCEKEY_ID", StringType.INSTANCE);
       alertQry.addScalar("AD_ROLE_ID", StringType.INSTANCE);
       alertQry.addScalar("AD_USER_ID", StringType.INSTANCE);
@@ -372,7 +374,8 @@
         + "), 0) <> coalesce(max(sd." + StorageDetail.PROPERTY_QUANTITYONHAND + "), 0)");
     tsdhqlWhere.append(" or coalesce(sum(t." + MaterialTransaction.PROPERTY_ORDERQUANTITY
         + "), 0) <> coalesce(max(sd." + StorageDetail.PROPERTY_ONHANDORDERQUANITY + "), 0))");
-    final Query tsdhql = OBDal.getInstance().getSession().createQuery(tsdhqlWhere.toString());
+    final Query<Object> tsdhql = OBDal.getInstance().getSession()
+        .createQuery(tsdhqlWhere.toString(), Object.class);
     tsdhql.setMaxResults(1);
     Object transactionStorageDetail = tsdhql.uniqueResult();
     if (transactionStorageDetail != null) {
@@ -471,6 +474,7 @@
     TriggerHandler.getInstance().disable();
     try {
       // Reset costs in m_transaction_cost
+      @SuppressWarnings("rawtypes")
       Query queryDelete = OBDal.getInstance().getSession()
           .createQuery("delete from " + TransactionCost.ENTITY_NAME);
       queryDelete.executeUpdate();
@@ -484,6 +488,7 @@
       update.append(" " + MaterialTransaction.PROPERTY_TRANSACTIONCOST + " = null");
       update.append(" where " + MaterialTransaction.PROPERTY_TRANSACTIONCOST + " <> 0");
       update.append(" or " + MaterialTransaction.PROPERTY_ISCOSTCALCULATED + " = true");
+      @SuppressWarnings("rawtypes")
       Query updateQry = OBDal.getInstance().getSession().createQuery(update.toString());
       updateQry.executeUpdate();
       OBDal.getInstance().flush();
@@ -510,10 +515,11 @@
         update.append(" set " + Costing.PROPERTY_CURRENCY + " = :currency");
         update.append(" where " + Costing.PROPERTY_CLIENT + ".id = :clientId");
         update.append(" and " + Costing.PROPERTY_CURRENCY + ".id <> :currencyId");
+        @SuppressWarnings("rawtypes")
         Query updateQry = OBDal.getInstance().getSession().createQuery(update.toString());
         updateQry.setParameter("currency", client.getCurrency());
-        updateQry.setString("clientId", client.getId());
-        updateQry.setString("currencyId", client.getCurrency().getId());
+        updateQry.setParameter("clientId", client.getId());
+        updateQry.setParameter("currencyId", client.getCurrency().getId());
         updateQry.executeUpdate();
       }
       OBDal.getInstance().flush();
@@ -532,6 +538,7 @@
     log4j.debug("Starting createRules() at: " + new Date());
 
     // Delete manually created rules.
+    @SuppressWarnings("rawtypes")
     Query delQry = OBDal.getInstance().getSession()
         .createQuery("delete from " + CostingRule.ENTITY_NAME);
     delQry.executeUpdate();
@@ -692,7 +699,8 @@
     select.append(" group by tc." + TransactionCost.PROPERTY_CURRENCY + ",");
     select.append("   tc." + TransactionCost.PROPERTY_ACCOUNTINGDATE);
 
-    Query trxQry = OBDal.getInstance().getSession().createQuery(select.toString());
+    Query<Object[]> trxQry = OBDal.getInstance().getSession()
+        .createQuery(select.toString(), Object[].class);
     trxQry.setParameter("product", productId);
     trxQry.setParameterList("orgs", orgs);
 
@@ -808,11 +816,12 @@
     where.append("     )");
     where.append("   and " + Costing.PROPERTY_COST + " is not null");
 
-    Query costingQry = OBDal.getInstance().getSession().createQuery(where.toString());
+    Query<Long> costingQry = OBDal.getInstance().getSession()
+        .createQuery(where.toString(), Long.class);
     costingQry.setParameter("client", clientId);
     costingQry.setParameterList("orgs", naturalTree);
     costingQry.setMaxResults(1);
-    return ((Long) costingQry.uniqueResult()).intValue();
+    return (costingQry.uniqueResult()).intValue();
   }
 
   private void updateTrxLegacyCosts(Costing _cost, int standardPrecision, Set<String> naturalTree) {
@@ -940,6 +949,7 @@
           insert.append(" left join iol." + ShipmentInOutLine.PROPERTY_SHIPMENTRECEIPT + " as io");
           insert.append(" where " + MaterialTransaction.PROPERTY_TRANSACTIONCOST + " is null");
           insert.append(" and t." + MaterialTransaction.PROPERTY_ORGANIZATION + ".id in (:orgs)");
+          @SuppressWarnings("rawtypes")
           Query insertQry = OBDal.getInstance().getSession().createQuery(insert.toString());
           insertQry.setParameterList("orgs", childOrgs);
           n1 += insertQry.executeUpdate();
@@ -954,6 +964,7 @@
           update.append(", " + MaterialTransaction.PROPERTY_ISPROCESSED + " = true");
           update.append(" where " + MaterialTransaction.PROPERTY_TRANSACTIONCOST + " is null");
           update.append(" and " + MaterialTransaction.PROPERTY_ORGANIZATION + ".id in (:orgs)");
+          @SuppressWarnings("rawtypes")
           Query updateQry = OBDal.getInstance().getSession().createQuery(update.toString());
           updateQry.setParameter("currency", org.getClient().getCurrency());
           updateQry.setParameterList("orgs", childOrgs);
@@ -1005,8 +1016,9 @@
     insert.append("    and u.id = '0'");
     insert.append("    and ar.id = :ar");
 
+    @SuppressWarnings("rawtypes")
     Query queryInsert = OBDal.getInstance().getSession().createQuery(insert.toString());
-    queryInsert.setString("ar", alertRule.getId());
+    queryInsert.setParameter("ar", alertRule.getId());
     int inserted = queryInsert.executeUpdate();
     log4j.debug("** inserted alert recipients: " + inserted);
   }
@@ -1075,12 +1087,13 @@
       insert.append("   or ad_isorgincluded(org." + Organization.PROPERTY_ID + ".id, p."
           + Product.PROPERTY_ORGANIZATION + ", p." + Product.PROPERTY_CLIENT + ".id) <> -1)");
 
+      @SuppressWarnings("rawtypes")
       Query queryInsert = OBDal.getInstance().getSession().createQuery(insert.toString());
       final SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
       String startingDate = dateFormatter.format(new Date());
-      queryInsert.setString("startingDate", startingDate);
-      queryInsert.setString("limitDate", startingDate);
-      queryInsert.setString("limitDate2", startingDate);
+      queryInsert.setParameter("startingDate", startingDate);
+      queryInsert.setParameter("limitDate", startingDate);
+      queryInsert.setParameter("limitDate2", startingDate);
       n = queryInsert.executeUpdate();
 
       OBDal.getInstance().flush();
--- a/src/org/openbravo/costing/CostingRuleProcess.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/costing/CostingRuleProcess.java	Tue Jul 24 10:44:21 2018 +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) 2012-2017 Openbravo SLU
+ * All portions are Copyright (C) 2012-2018 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  *************************************************************************
@@ -30,9 +30,9 @@
 
 import org.apache.commons.lang.time.DateUtils;
 import org.apache.log4j.Logger;
-import org.hibernate.Query;
 import org.hibernate.ScrollMode;
 import org.hibernate.ScrollableResults;
+import org.hibernate.query.Query;
 import org.openbravo.base.exception.OBException;
 import org.openbravo.base.provider.OBProvider;
 import org.openbravo.dal.core.OBContext;
@@ -311,10 +311,11 @@
     insert.append(" and t." + MaterialTransaction.PROPERTY_ACTIVE + " = true");
     insert.append(" and t." + MaterialTransaction.PROPERTY_CLIENT + ".id = :client");
 
+    @SuppressWarnings("rawtypes")
     Query queryInsert = OBDal.getInstance().getSession().createQuery(insert.toString());
     queryInsert.setParameterList("orgs", childOrgs);
-    queryInsert.setTimestamp("date", date);
-    queryInsert.setString("client", client.getId());
+    queryInsert.setParameter("date", date);
+    queryInsert.setParameter("client", client.getId());
     int n1 = queryInsert.executeUpdate();
     log4j.debug("InitializeOldTrx inserted " + n1 + " records. Took: "
         + (System.currentTimeMillis() - t1) + " ms.");
@@ -333,11 +334,12 @@
     update.append(" and " + MaterialTransaction.PROPERTY_ACTIVE + " = true");
     update.append(" and " + MaterialTransaction.PROPERTY_CLIENT + ".id = :client");
 
+    @SuppressWarnings("rawtypes")
     Query queryUpdate = OBDal.getInstance().getSession().createQuery(update.toString());
     queryUpdate.setParameter("currency", client.getCurrency());
     queryUpdate.setParameterList("orgs", childOrgs);
-    queryUpdate.setTimestamp("date", date);
-    queryUpdate.setString("client", client.getId());
+    queryUpdate.setParameter("date", date);
+    queryUpdate.setParameter("client", client.getId());
     int n2 = queryUpdate.executeUpdate();
     log4j.debug("InitializeOldTrx updated " + n2 + " records. Took: "
         + (System.currentTimeMillis() - t2) + " ms.");
@@ -481,10 +483,11 @@
     select.append(", trx." + MaterialTransaction.PROPERTY_UOM + ".id");
     select.append(", trx." + MaterialTransaction.PROPERTY_ORDERUOM + ".id");
 
+    @SuppressWarnings("rawtypes")
     Query stockLinesQry = OBDal.getInstance().getSession().createQuery(select.toString());
     stockLinesQry.setParameterList("orgs", childOrgs);
     if (date != null) {
-      stockLinesQry.setTimestamp("date", date);
+      stockLinesQry.setParameter("date", date);
     }
     stockLinesQry.setFetchSize(1000);
     ScrollableResults stockLines = stockLinesQry.scroll(ScrollMode.FORWARD_ONLY);
@@ -732,9 +735,10 @@
         + MaterialTransaction.PROPERTY_PHYSICALINVENTORYLINE + ".id");
     update.append(" )");
 
+    @SuppressWarnings("rawtypes")
     Query queryUpdate = OBDal.getInstance().getSession().createQuery(update.toString());
-    queryUpdate.setTimestamp("date", startingDate);
-    queryUpdate.setString("cr", ruleId);
+    queryUpdate.setParameter("date", startingDate);
+    queryUpdate.setParameter("cr", ruleId);
     queryUpdate.executeUpdate();
 
     OBDal.getInstance().flush();
@@ -742,6 +746,7 @@
   }
 
   private void deleteLastTransaction() {
+    @SuppressWarnings("rawtypes")
     Query queryDelete = OBDal.getInstance().getSession()
         .createQuery("delete from " + TransactionLast.ENTITY_NAME);
     queryDelete.executeUpdate();
--- a/src/org/openbravo/costing/CostingUtils.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/costing/CostingUtils.java	Tue Jul 24 10:44:21 2018 +0200
@@ -31,10 +31,10 @@
 
 import org.apache.commons.lang.StringUtils;
 import org.apache.log4j.Logger;
-import org.hibernate.Query;
 import org.hibernate.ScrollMode;
 import org.hibernate.ScrollableResults;
 import org.hibernate.criterion.Restrictions;
+import org.hibernate.query.Query;
 import org.openbravo.base.exception.OBException;
 import org.openbravo.base.session.OBPropertiesProvider;
 import org.openbravo.base.structure.BaseOBObject;
@@ -437,7 +437,8 @@
     } else {
       select.append(" and trx." + MaterialTransaction.PROPERTY_ORGANIZATION + ".id in (:orgs)");
     }
-    Query trxQry = OBDal.getInstance().getSession().createQuery(select.toString());
+    Query<BigDecimal> trxQry = OBDal.getInstance().getSession()
+        .createQuery(select.toString(), BigDecimal.class);
     trxQry.setParameter("product", product.getId());
     trxQry.setParameter("dateTo", dateTo);
     if (existsCumulatedStock) {
@@ -460,7 +461,7 @@
     } else {
       trxQry.setParameterList("orgs", orgs);
     }
-    BigDecimal stock = (BigDecimal) trxQry.uniqueResult();
+    BigDecimal stock = trxQry.uniqueResult();
     if (stock == null) {
       stock = BigDecimal.ZERO;
     }
@@ -571,7 +572,8 @@
     select.append(" group by tc." + TransactionCost.PROPERTY_CURRENCY + ",");
     select.append(" tc." + TransactionCost.PROPERTY_ACCOUNTINGDATE);
 
-    Query trxQry = OBDal.getInstance().getSession().createQuery(select.toString());
+    Query<Object[]> trxQry = OBDal.getInstance().getSession()
+        .createQuery(select.toString(), Object[].class);
     trxQry.setParameter("product", product.getId());
     trxQry.setParameter("dateTo", dateTo);
     if (existsCumulatedValuation) {
@@ -712,11 +714,12 @@
     select.append(" from " + MaterialTransaction.ENTITY_NAME + " as trx");
     select.append(" where trx." + MaterialTransaction.PROPERTY_ISCOSTCALCULATED + " = true");
     select.append("   and trx." + MaterialTransaction.PROPERTY_ORGANIZATION + ".id in (:orgs)");
-    Query trxQry = OBDal.getInstance().getSession().createQuery(select.toString());
+    Query<Date> trxQry = OBDal.getInstance().getSession()
+        .createQuery(select.toString(), Date.class);
     trxQry.setParameterList("orgs", orgs);
-    Object maxDate = trxQry.uniqueResult();
+    Date maxDate = trxQry.uniqueResult();
     if (maxDate != null) {
-      return (Date) maxDate;
+      return maxDate;
     }
     return null;
   }
@@ -849,7 +852,8 @@
     where.append(" order by w." + Warehouse.PROPERTY_NAME + " desc");
     where.append(" , il." + InventoryCountLine.PROPERTY_LINENO + " desc");
 
-    Query qry = OBDal.getInstance().getSession().createQuery(where.toString());
+    Query<String> qry = OBDal.getInstance().getSession()
+        .createQuery(where.toString(), String.class);
     OBDal.getInstance().refresh(trx.getPhysicalInventoryLine().getPhysInventory());
     qry.setParameter("iaul", trx.getPhysicalInventoryLine().getPhysInventory()
         .getInventoryAmountUpdateLineInventoriesInitInventoryList().get(0).getCaInventoryamtline());
@@ -857,7 +861,7 @@
       qry.setParameter("warehouse", trx.getStorageBin().getWarehouse());
     }
     qry.setMaxResults(1);
-    return StringUtils.equals(trx.getId(), (String) qry.uniqueResult());
+    return StringUtils.equals(trx.getId(), qry.uniqueResult());
   }
 
   @Deprecated
@@ -881,7 +885,8 @@
     where.append("               and l." + Locator.PROPERTY_CLIENT + " = c)");
     where.append(" and c = :client");
 
-    Query qry = OBDal.getInstance().getSession().createQuery(where.toString());
+    Query<Client> qry = OBDal.getInstance().getSession()
+        .createQuery(where.toString(), Client.class);
     qry.setParameter("client", client);
     qry.setMaxResults(1);
     return !qry.list().isEmpty();
@@ -900,7 +905,8 @@
     where.append("               where invs." + InventoryStatus.PROPERTY_OVERISSUE + " = true");
     where.append("               and io." + ShipmentInOut.PROPERTY_ID + " = :shipmentInOutID)");
 
-    Query qry = OBDal.getInstance().getSession().createQuery(where.toString());
+    Query<Client> qry = OBDal.getInstance().getSession()
+        .createQuery(where.toString(), Client.class);
     qry.setParameter("shipmentInOutID", shipmentInOutId);
     qry.setMaxResults(1);
     return !qry.list().isEmpty();
--- a/src/org/openbravo/costing/FixBackdatedTransactionsProcess.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/costing/FixBackdatedTransactionsProcess.java	Tue Jul 24 10:44:21 2018 +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) 2014-2017 Openbravo SLU
+ * All portions are Copyright (C) 2014-2018 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  *************************************************************************
@@ -25,9 +25,9 @@
 
 import org.codehaus.jettison.json.JSONException;
 import org.codehaus.jettison.json.JSONObject;
-import org.hibernate.Query;
 import org.hibernate.ScrollMode;
 import org.hibernate.ScrollableResults;
+import org.hibernate.query.Query;
 import org.openbravo.base.exception.OBException;
 import org.openbravo.client.application.process.BaseProcessActionHandler;
 import org.openbravo.dal.core.OBContext;
@@ -195,11 +195,12 @@
     }
     select.append(" order by trx." + MaterialTransaction.PROPERTY_MOVEMENTDATE);
 
-    Query stockLinesQry = OBDal.getInstance().getSession().createQuery(select.toString());
+    Query<MaterialTransaction> stockLinesQry = OBDal.getInstance().getSession()
+        .createQuery(select.toString(), MaterialTransaction.class);
     stockLinesQry.setParameterList("orgs", childOrgs);
-    stockLinesQry.setTimestamp("startDate", startDate);
+    stockLinesQry.setParameter("startDate", startDate);
     if (endDate != null) {
-      stockLinesQry.setTimestamp("endDate", endDate);
+      stockLinesQry.setParameter("endDate", endDate);
     }
 
     stockLinesQry.setFetchSize(1000);
--- a/src/org/openbravo/costing/InventoryAmountUpdateProcess.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/costing/InventoryAmountUpdateProcess.java	Tue Jul 24 10:44:21 2018 +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) 2014-2016 Openbravo SLU
+ * All portions are Copyright (C) 2014-2018 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -27,10 +27,10 @@
 import java.util.Set;
 
 import org.codehaus.jettison.json.JSONObject;
-import org.hibernate.Query;
 import org.hibernate.ScrollMode;
 import org.hibernate.ScrollableResults;
 import org.hibernate.criterion.Restrictions;
+import org.hibernate.query.Query;
 import org.openbravo.base.provider.OBProvider;
 import org.openbravo.client.kernel.BaseActionHandler;
 import org.openbravo.dal.core.OBContext;
@@ -282,16 +282,17 @@
         subSelect.append("   and trx." + MaterialTransaction.PROPERTY_ORGANIZATION
             + ".id in (:orgs)");
 
-        Query trxsubQry = OBDal.getInstance().getSession().createQuery(subSelect.toString());
+        Query<Date> trxsubQry = OBDal.getInstance().getSession()
+            .createQuery(subSelect.toString(), Date.class);
         trxsubQry.setParameter("date", localDate);
         trxsubQry.setParameter("product", product.getId());
         if (warehouse != null) {
           trxsubQry.setParameter("warehouse", warehouse.getId());
         }
         trxsubQry.setParameterList("orgs", childOrgs);
-        Object trxprocessDate = trxsubQry.uniqueResult();
+        Date trxprocessDate = trxsubQry.uniqueResult();
         if (trxprocessDate != null) {
-          localDate = (Date) trxprocessDate;
+          localDate = trxprocessDate;
           select.append("   and trx." + MaterialTransaction.PROPERTY_TRANSACTIONPROCESSDATE
               + " < :date");
         } else {
@@ -316,10 +317,11 @@
     select.append(", trx." + MaterialTransaction.PROPERTY_UOM + ".id");
     select.append(", trx." + MaterialTransaction.PROPERTY_ORDERUOM + ".id");
 
-    Query stockLinesQry = OBDal.getInstance().getSession().createQuery(select.toString());
+    Query<Object[]> stockLinesQry = OBDal.getInstance().getSession()
+        .createQuery(select.toString(), Object[].class);
     stockLinesQry.setParameterList("orgs", childOrgs);
     if (localDate != null) {
-      stockLinesQry.setTimestamp("date", localDate);
+      stockLinesQry.setParameter("date", localDate);
     }
     if (warehouse != null) {
       stockLinesQry.setParameter("warehouse", warehouse);
--- a/src/org/openbravo/costing/LCMatchingProcess.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/costing/LCMatchingProcess.java	Tue Jul 24 10:44:21 2018 +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) 2014-2015 Openbravo SLU
+ * All portions are Copyright (C) 2014-2018 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  *************************************************************************
@@ -30,11 +30,11 @@
 import org.apache.commons.lang.StringUtils;
 import org.codehaus.jettison.json.JSONException;
 import org.codehaus.jettison.json.JSONObject;
-import org.hibernate.Query;
 import org.hibernate.ScrollMode;
 import org.hibernate.ScrollableResults;
 import org.hibernate.criterion.Projections;
 import org.hibernate.criterion.Restrictions;
+import org.hibernate.query.Query;
 import org.openbravo.base.exception.OBException;
 import org.openbravo.base.util.OBClassLoader;
 import org.openbravo.base.weld.WeldUtils;
@@ -171,7 +171,8 @@
     hql.append(" group by rla." + LCReceipt.PROPERTY_GOODSSHIPMENTLINE + ".id");
     hql.append(" order by trxprocessdate, amt");
 
-    Query qryLCRLA = OBDal.getInstance().getSession().createQuery(hql.toString());
+    Query<Object[]> qryLCRLA = OBDal.getInstance().getSession()
+        .createQuery(hql.toString(), Object[].class);
     qryLCRLA.setParameter("lcc", lcCost);
 
     ScrollableResults receiptamts = qryLCRLA.scroll(ScrollMode.FORWARD_ONLY);
--- a/src/org/openbravo/costing/LandedCostDistributionByAmount.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/costing/LandedCostDistributionByAmount.java	Tue Jul 24 10:44:21 2018 +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) 2014-2016 Openbravo SLU
+ * All portions are Copyright (C) 2014-2018 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  *************************************************************************
@@ -22,9 +22,9 @@
 import java.math.RoundingMode;
 import java.util.Date;
 
-import org.hibernate.Query;
 import org.hibernate.ScrollableResults;
 import org.hibernate.criterion.Restrictions;
+import org.hibernate.query.Query;
 import org.openbravo.base.provider.OBProvider;
 import org.openbravo.dal.service.OBCriteria;
 import org.openbravo.dal.service.OBDal;
@@ -159,7 +159,8 @@
       qry.append(" , sum(tc." + TransactionCost.PROPERTY_COST + ")");
     }
 
-    Query qryReceiptCosts = OBDal.getInstance().getSession().createQuery(qry.toString());
+    Query<Object[]> qryReceiptCosts = OBDal.getInstance().getSession()
+        .createQuery(qry.toString(), Object[].class);
     qryReceiptCosts.setParameter("landedCost", landedCost.getId());
 
     return qryReceiptCosts.scroll();
--- a/src/org/openbravo/costing/LandedCostProcess.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/costing/LandedCostProcess.java	Tue Jul 24 10:44:21 2018 +0200
@@ -31,11 +31,11 @@
 import org.apache.commons.lang.StringUtils;
 import org.codehaus.jettison.json.JSONException;
 import org.codehaus.jettison.json.JSONObject;
-import org.hibernate.Query;
 import org.hibernate.ScrollMode;
 import org.hibernate.ScrollableResults;
 import org.hibernate.criterion.Projections;
 import org.hibernate.criterion.Restrictions;
+import org.hibernate.query.Query;
 import org.openbravo.base.exception.OBException;
 import org.openbravo.base.provider.OBProvider;
 import org.openbravo.base.util.OBClassLoader;
@@ -239,7 +239,8 @@
     hql.append(" , gsl." + ShipmentInOutLine.PROPERTY_LINENO);
     hql.append(" , amt");
 
-    Query qryLCRLA = OBDal.getInstance().getSession().createQuery(hql.toString());
+    Query<Object[]> qryLCRLA = OBDal.getInstance().getSession()
+        .createQuery(hql.toString(), Object[].class);
     qryLCRLA.setParameter("lc", landedCost);
 
     ScrollableResults receiptamts = qryLCRLA.scroll(ScrollMode.FORWARD_ONLY);
--- a/src/org/openbravo/costing/PriceDifferenceUtil.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/costing/PriceDifferenceUtil.java	Tue Jul 24 10:44:21 2018 +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 Openbravo SLU
+ * All portions are Copyright (C) 2017-2018 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  *************************************************************************
@@ -27,7 +27,7 @@
 
 import org.apache.commons.lang.StringUtils;
 import org.codehaus.jettison.json.JSONException;
-import org.hibernate.Query;
+import org.hibernate.query.Query;
 import org.openbravo.dal.core.OBContext;
 import org.openbravo.dal.security.OrganizationStructureProvider;
 import org.openbravo.dal.service.OBDal;
@@ -55,6 +55,7 @@
 
     Set<String> products = new HashSet<String>();
     products.addAll(productIds);
+    @SuppressWarnings("rawtypes")
     Query update = OBDal.getInstance().getSession().createQuery(strUpdate);
 
     if (!productIds.isEmpty()) {
@@ -62,7 +63,7 @@
     }
     update.setParameterList("orgIds",
         new OrganizationStructureProvider().getChildTree(organization.getId(), true));
-    update.setDate("date", movementdate);
+    update.setParameter("date", movementdate);
     update.setParameter("clientId", OBContext.getOBContext().getCurrentClient().getId());
 
     update.executeUpdate();
--- a/src/org/openbravo/costing/ResetStockValuation.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/costing/ResetStockValuation.java	Tue Jul 24 10:44:21 2018 +0200
@@ -7,7 +7,7 @@
 import org.apache.log4j.Logger;
 import org.codehaus.jettison.json.JSONException;
 import org.codehaus.jettison.json.JSONObject;
-import org.hibernate.Query;
+import org.hibernate.query.Query;
 import org.openbravo.client.application.process.BaseProcessActionHandler;
 import org.openbravo.dal.core.OBContext;
 import org.openbravo.dal.service.OBDal;
@@ -58,6 +58,7 @@
         sql.append("\n and sv." + StockValuation.PROPERTY_ORGANIZATION + ".id = :org");
       }
 
+      @SuppressWarnings("rawtypes")
       Query delQry = OBDal.getInstance().getSession().createQuery(sql.toString());
       delQry.setParameter("client", OBContext.getOBContext().getCurrentClient().getId());
       if (strOrgID != null) {
--- a/src/org/openbravo/costing/StandardCostAdjustment.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/costing/StandardCostAdjustment.java	Tue Jul 24 10:44:21 2018 +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) 2014-2015 Openbravo SLU
+ * All portions are Copyright (C) 2014-2018 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  *************************************************************************
@@ -23,9 +23,9 @@
 import java.util.HashMap;
 import java.util.Set;
 
-import org.hibernate.Query;
 import org.hibernate.ScrollMode;
 import org.hibernate.ScrollableResults;
+import org.hibernate.query.Query;
 import org.openbravo.base.structure.BaseOBObject;
 import org.openbravo.client.kernel.ComponentProvider;
 import org.openbravo.costing.CostingAlgorithm.CostDimension;
@@ -156,7 +156,8 @@
     }
     dateWhere.append(" order by trx." + MaterialTransaction.PROPERTY_MOVEMENTDATE);
 
-    Query dateQry = OBDal.getInstance().getSession().createQuery(dateWhere.toString());
+    Query<Date> dateQry = OBDal.getInstance().getSession()
+        .createQuery(dateWhere.toString(), Date.class);
     dateQry.setParameter("client", trx.getClient());
     dateQry.setParameterList("orgs", orgs);
     dateQry.setParameter("product", trx.getProduct());
@@ -166,7 +167,7 @@
       dateQry.setParameter("warehouse", warehouse);
     }
     dateQry.setMaxResults(1);
-    Date date = (Date) dateQry.uniqueResult();
+    Date date = dateQry.uniqueResult();
 
     // Get transactions with movement/process date after trx and before next Inventory Amount Update
     // (include closing inventory lines and exclude opening inventory lines of it)
@@ -209,7 +210,8 @@
       where.append(" order by trx." + MaterialTransaction.PROPERTY_TRANSACTIONPROCESSDATE);
     }
 
-    Query qry = OBDal.getInstance().getSession().createQuery(where.toString());
+    Query<String> qry = OBDal.getInstance().getSession()
+        .createQuery(where.toString(), String.class);
     qry.setParameter("client", trx.getClient());
     qry.setParameterList("orgs", orgs);
     qry.setParameter("product", trx.getProduct());
@@ -267,7 +269,8 @@
     }
     where.append(" order by min(trx." + MaterialTransaction.PROPERTY_MOVEMENTDATE + ")");
 
-    Query qry = OBDal.getInstance().getSession().createQuery(where.toString());
+    Query<String> qry = OBDal.getInstance().getSession()
+        .createQuery(where.toString(), String.class);
     qry.setParameter("client", trx.getClient());
     qry.setParameterList("orgs", orgs);
     qry.setParameter("product", trx.getProduct());
--- a/src/org/openbravo/dal/core/DalInitializingTask.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/dal/core/DalInitializingTask.java	Tue Jul 24 10:44:21 2018 +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-2010 Openbravo SLU 
+ * All portions are Copyright (C) 2008-2018 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -87,6 +87,7 @@
    */
   @Override
   public void execute() {
+
     // initAntConsoleLogging();
     OBProvider.getInstance().register(OBClassLoader.class, OBClassLoader.ClassOBClassLoader.class,
         false);
@@ -99,6 +100,7 @@
     }
 
     if (!DalLayerInitializer.getInstance().isInitialized()) {
+
       log.debug("initializating dal layer, getting properties from " + getPropertiesFile());
       OBPropertiesProvider.getInstance().setProperties(getPropertiesFile());
 
@@ -106,7 +108,18 @@
         OBConfigFileProvider.getInstance().setFileLocation(getProviderConfigDirectory());
       }
 
-      DalLayerInitializer.getInstance().initialize(rereadConfigs);
+      // Set the current class class loader as the context class loader to initialize the DAL layer.
+      // Otherwise, when executing this kind of tasks in JDK11 using ant, the selected context class
+      // loader is not able to find the required JAXBContext instance implementation required to
+      // build the Hibernate mapping.
+      ClassLoader ctxClassLoader = Thread.currentThread().getContextClassLoader();
+      ClassLoader classClassLoader = getClass().getClassLoader();
+      Thread.currentThread().setContextClassLoader(classClassLoader);
+      try {
+        DalLayerInitializer.getInstance().initialize(rereadConfigs);
+      } finally {
+        Thread.currentThread().setContextClassLoader(ctxClassLoader);
+      }
     } else {
       log.debug("Dal Layer already initialized");
     }
--- a/src/org/openbravo/dal/core/DalLayerInitializer.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/dal/core/DalLayerInitializer.java	Tue Jul 24 10:44:21 2018 +0200
@@ -28,6 +28,7 @@
 import org.openbravo.base.provider.OBConfigFileProvider;
 import org.openbravo.base.provider.OBProvider;
 import org.openbravo.base.provider.OBSingleton;
+import org.openbravo.base.session.OBPropertiesProvider;
 import org.openbravo.base.session.SessionFactoryController;
 import org.openbravo.base.weld.WeldUtils;
 
@@ -82,6 +83,12 @@
     SessionFactoryController.setInstance(getDalSessionFactoryController());
     SessionFactoryController.getInstance().initialize();
 
+    if (isUsingExternalConnectionPool()) {
+      // when the session factory is created by the SessionFactoryController, a basic Hibernate pool
+      // is also created, let's close it to prevent leaked connections
+      SessionFactoryController.getInstance().closeHibernatePool();
+    }
+
     // reset the session
     SessionHandler.deleteSessionHandler();
 
@@ -121,6 +128,12 @@
     this.sqlFunctions = sqlFunctions;
   }
 
+  private boolean isUsingExternalConnectionPool() {
+    String poolClassName = OBPropertiesProvider.getInstance().getOpenbravoProperties()
+        .getProperty("db.externalPoolClassName");
+    return poolClassName != null && !"".equals(poolClassName);
+  }
+
   public boolean isInitialized() {
     return initialized;
   }
--- a/src/org/openbravo/dal/core/DalMappingGenerator.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/dal/core/DalMappingGenerator.java	Tue Jul 24 10:44:21 2018 +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-2017 Openbravo SLU 
+ * All portions are Copyright (C) 2008-2018 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -52,15 +52,14 @@
 public class DalMappingGenerator implements OBSingleton {
   private static final Logger log = Logger.getLogger(DalMappingGenerator.class);
 
-  private final static String HIBERNATE_FILE_PROPERTY = "hibernate.hbm.file";
-  private final static String HIBERNATE_READ_FILE_PROPERTY = "hibernate.hbm.readFile";
+  private static final String HIBERNATE_FILE_PROPERTY = "hibernate.hbm.file";
+  private static final String HIBERNATE_READ_FILE_PROPERTY = "hibernate.hbm.readFile";
 
-  private final static String TEMPLATE_FILE = "template.hbm.xml";
-  private final static String MAIN_TEMPLATE_FILE = "template_main.hbm.xml";
-  // private final static char TAB = '\t';
-  private final static String TAB2 = "\t\t";
-  private final static String TAB3 = "\t\t\t";
-  private final static char NL = '\n';
+  private static final String TEMPLATE_FILE = "template.hbm.xml";
+  private static final String MAIN_TEMPLATE_FILE = "template_main.hbm.xml";
+  private static final String TAB2 = "\t\t";
+  private static final String TAB3 = "\t\t\t";
+  private static final char NL = '\n';
 
   private static DalMappingGenerator instance = new DalMappingGenerator();
 
@@ -84,8 +83,7 @@
    * @return the generated Hibernate mapping (corresponds to what is found in a hbm.xml file)
    */
   public String generateMapping() {
-    final String hibernateFileLocation = OBPropertiesProvider.getInstance()
-        .getOpenbravoProperties().getProperty(HIBERNATE_FILE_PROPERTY);
+    final String hibernateFileLocation = getHibernateFileLocation();
 
     // If readMappingFromFile is true and the mapping is already generated to a file, this file will
     // be read instead of generating a new one. Useful while developing changes in mapping to edit
@@ -111,7 +109,7 @@
     final StringBuilder sb = new StringBuilder();
     for (final Entity e : mp.getModel()) {
       // Do not map datasource based tables
-      if (!e.isDataSourceBased() && !e.isVirtualEntity()) {
+      if (!e.isDataSourceBased() && !e.isVirtualEntity() && e.getMappingClass() != null) {
         final String entityMapping = generateMapping(e);
         sb.append(entityMapping);
       }
@@ -141,11 +139,16 @@
     return result;
   }
 
+  String getHibernateFileLocation() {
+    return OBPropertiesProvider.getInstance().getOpenbravoProperties()
+        .getProperty(HIBERNATE_FILE_PROPERTY);
+  }
+
   private String generateMapping(Entity entity) {
     String hbm = getClassTemplateContents();
     hbm = hbm.replaceAll("mappingName", entity.getName());
     hbm = hbm.replaceAll("tableName", entity.getTableName());
-    hbm = hbm.replaceAll("ismutable", entity.isMutable() + "");
+    hbm = hbm.replaceAll("ismutable", Boolean.toString(entity.isMutable()));
 
     if (entity.getMappingClass() != null) {
       hbm = hbm.replaceAll("<class", "<class name=\"" + entity.getClassName() + "\" ");
@@ -155,13 +158,6 @@
     final StringBuilder content = new StringBuilder();
 
     content.append(TAB2);
-    if (entity.getMappingClass() == null) {
-      content.append("<tuplizer entity-mode=\"dynamic-map\" "
-          + "class=\"org.openbravo.dal.core.OBDynamicTuplizer\"/>\n\n");
-    } else {
-      content.append("<tuplizer entity-mode=\"pojo\" "
-          + "class=\"org.openbravo.dal.core.OBTuplizer\"/>\n\n");
-    }
 
     if (entity.hasCompositeId()) {
       content.append(generateCompositeID(entity));
@@ -170,7 +166,7 @@
     }
     content.append(NL);
 
-    List<Property> computedColumns = new ArrayList<Property>();
+    List<Property> computedColumns = new ArrayList<>();
     // now handle the standard columns
     for (final Property p : entity.getProperties()) {
       if (p.isId()) { // && p.isPrimitive()) { // handled separately
@@ -221,20 +217,18 @@
     hbm = hbm.replaceAll("ismutable", "false");
 
     final StringBuilder content = new StringBuilder();
-    content.append(TAB2
-        + "<tuplizer entity-mode=\"pojo\" class=\"org.openbravo.dal.core.OBTuplizer\"/>" + NL + NL);
     content.append(generateStandardID(entity) + NL);
 
     if (entity.isClientEnabled()) {
       content
           .append(TAB2
-              + "<many-to-one name=\"client\" column=\"AD_Client_ID\" not-null=\"true\" update=\"false\" insert=\"false\" entity-name=\"ADClient\" access=\"org.openbravo.dal.core.OBDynamicPropertyHandler\"/>"
+              + "<many-to-one name=\"client\" column=\"AD_Client_ID\" not-null=\"true\" update=\"false\" insert=\"false\" entity-name=\"ADClient\" access=\"org.openbravo.dal.core.DalPropertyAccessStrategy\"/>"
               + NL);
     }
     if (entity.isOrganizationEnabled()) {
       content
           .append(TAB2
-              + "<many-to-one name=\"organization\" column=\"AD_Org_ID\" not-null=\"true\" update=\"false\" insert=\"false\" entity-name=\"Organization\" access=\"org.openbravo.dal.core.OBDynamicPropertyHandler\"/>"
+              + "<many-to-one name=\"organization\" column=\"AD_Org_ID\" not-null=\"true\" update=\"false\" insert=\"false\" entity-name=\"Organization\" access=\"org.openbravo.dal.core.DalPropertyAccessStrategy\"/>"
               + NL);
     }
     content.append(NL);
@@ -252,10 +246,10 @@
   private String generateComputedColumnsMapping(Entity entity) {
     Check.isTrue(entity.getIdProperties().size() == 1,
         "Computed columns are not supported in entities with composited ID");
-    StringBuffer sb = new StringBuffer();
+    StringBuilder sb = new StringBuilder();
     final Property p = entity.getIdProperties().get(0);
     sb.append(TAB2
-        + "<many-to-one name=\"_computedColumns\" update=\"false\" insert=\"false\" access=\"org.openbravo.dal.core.OBDynamicPropertyHandler\" ");
+        + "<many-to-one name=\"_computedColumns\" update=\"false\" insert=\"false\" access=\"org.openbravo.dal.core.DalPropertyAccessStrategy\" ");
     sb.append("column=\"" + p.getColumnName() + "\" ");
     sb.append("entity-name=\"" + getComputedColumnsEntityName(entity) + "\"/>" + NL);
     return sb.toString();
@@ -273,7 +267,7 @@
     if (p.getHibernateType() == Object.class) {
       return "";
     }
-    final StringBuffer sb = new StringBuffer();
+    final StringBuilder sb = new StringBuilder();
     sb.append(TAB2 + "<property name=\"" + p.getName() + "\"");
     sb.append(getAccessorAttribute());
     String type;
@@ -283,7 +277,7 @@
       type = p.getHibernateType().getName();
     }
     if (p.isBoolean()) {
-      type = YesNoType.class.getName(); // "yes_no";
+      type = YesNoType.class.getName();
     }
     sb.append(" type=\"" + type + "\"");
 
@@ -298,9 +292,8 @@
       sb.append(" not-null=\"true\"");
     }
 
-    // ignoring isUpdatable for now as this is primarily used
+    // ignoring p.isUpdatable() for now as this is primarily used
     // for ui and not for background processes
-    // if (!p.isUpdatable() || p.isInactive()) {
 
     if (p.isInactive() || p.getEntity().isView() || p.getSqlLogic() != null) {
       sb.append(" update=\"false\"");
@@ -320,7 +313,7 @@
             + p.getEntity().getName() + "-->" + NL;
       }
     }
-    final StringBuffer sb = new StringBuffer();
+    final StringBuilder sb = new StringBuilder();
     if (p.isOneToOne()) {
       final String name = p.getSimpleTypeName().substring(0, 1).toLowerCase()
           + p.getSimpleTypeName().substring(1);
@@ -358,7 +351,6 @@
         sb.append(" insert=\"false\"");
       }
     }
-    // sb.append(" cascade=\"save-update\"");
 
     // to prevent cascade errors that the parent is saved after the child
     // this is handled by the DataImportService.insertObjectGraph
@@ -380,10 +372,10 @@
   }
 
   private String generateOneToMany(Property p) {
-    final StringBuffer sb = new StringBuffer();
-    StringBuffer order = new StringBuffer();
+    final StringBuilder sb = new StringBuilder();
+    StringBuilder order = new StringBuilder();
     if (p.isOneToMany()) {
-      if (p.getTargetEntity().getOrderByProperties().size() > 0) {
+      if (!p.getTargetEntity().getOrderByProperties().isEmpty()) {
         order.append("order-by=\"");
         for (final Property po : p.getTargetEntity().getOrderByProperties()) {
           order.append(po.getColumnName() + " ASC,");
@@ -423,7 +415,7 @@
         "Method can only handle primary keys with one column in entity " + entity.getName()
             + ". It has " + entity.getIdProperties().size());
     final Property p = entity.getIdProperties().get(0);
-    final StringBuffer sb = new StringBuffer();
+    final StringBuilder sb = new StringBuilder();
     sb.append(TAB2 + "<id name=\"" + p.getName() + "\" type=\"string\" " + getAccessorAttribute()
         + " column=\"" + p.getColumnName() + "\" unsaved-value=\"null\">" + NL);
     if (p.getIdBasedOnProperty() != null) {
@@ -439,13 +431,13 @@
   }
 
   private String getAccessorAttribute() {
-    return " access=\"" + OBDynamicPropertyHandler.class.getName() + "\"";
+    return " access=\"" + DalPropertyAccessStrategy.class.getName() + "\"";
   }
 
   private String generateCompositeID(Entity e) {
     Check.isTrue(e.hasCompositeId(),
         "Method can only handle primary keys with more than one column");
-    final StringBuffer sb = new StringBuffer();
+    final StringBuilder sb = new StringBuilder();
     sb.append(TAB2 + "<composite-id name=\"id\" class=\"" + e.getClassName() + "$Id\""
         + getAccessorAttribute() + ">" + NL);
     final Property compId = e.getIdProperties().get(0);
@@ -488,7 +480,7 @@
       final BufferedReader br = new BufferedReader(fr);
       try {
         String line;
-        final StringBuffer sb = new StringBuffer();
+        final StringBuilder sb = new StringBuilder();
         while ((line = br.readLine()) != null) {
           sb.append(line + "\n");
         }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/org/openbravo/dal/core/DalPropertyAccess.java	Tue Jul 24 10:44:21 2018 +0200
@@ -0,0 +1,183 @@
+/*
+ *************************************************************************
+ * The contents of this file are subject to the Openbravo  Public  License
+ * Version  1.1  (the  "License"),  being   the  Mozilla   Public  License
+ * Version 1.1  with a permitted attribution clause; you may not  use this
+ * file except in compliance with the License. You  may  obtain  a copy of
+ * the License at http://www.openbravo.com/legal/license.html 
+ * Software distributed under the License  is  distributed  on  an "AS IS"
+ * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
+ * License for the specific  language  governing  rights  and  limitations
+ * 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 Rights Reserved. 
+ * Contributor(s):  ______________________________________.
+ ************************************************************************
+ */
+
+package org.openbravo.dal.core;
+
+import java.lang.reflect.Member;
+import java.lang.reflect.Method;
+import java.util.Map;
+
+import org.hibernate.engine.spi.SessionFactoryImplementor;
+import org.hibernate.engine.spi.SharedSessionContractImplementor;
+import org.hibernate.property.access.spi.Getter;
+import org.hibernate.property.access.spi.PropertyAccess;
+import org.hibernate.property.access.spi.PropertyAccessStrategy;
+import org.hibernate.property.access.spi.Setter;
+import org.openbravo.base.model.ModelProvider;
+import org.openbravo.base.model.NamingUtil;
+import org.openbravo.base.model.Property;
+import org.openbravo.base.structure.BaseOBObject;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Describes access to a particular DAL entity property in terms of getting and setting its value.
+ * The access is built via a get/set pair. The instances of this class are obtained from the
+ * {@link DalPropertyAccessStrategy} class.
+ */
+@SuppressWarnings("rawtypes")
+class DalPropertyAccess implements PropertyAccess {
+
+  private static final Logger log = LoggerFactory.getLogger(DalPropertyAccess.class);
+
+  private final PropertyAccessStrategy strategy;
+  private final GetterMethod getter;
+  private final SetterMethod setter;
+
+  DalPropertyAccess(PropertyAccessStrategy strategy, Class containerJavaType,
+      final String propertyName) {
+    this.strategy = strategy;
+    this.getter = new GetterMethod(containerJavaType, propertyName);
+    this.setter = new SetterMethod(containerJavaType, propertyName);
+  }
+
+  @Override
+  public PropertyAccessStrategy getPropertyAccessStrategy() {
+    return strategy;
+  }
+
+  @Override
+  public Getter getGetter() {
+    return getter;
+  }
+
+  @Override
+  public Setter getSetter() {
+    return setter;
+  }
+
+  private static class GetterMethod implements Getter {
+    private static final long serialVersionUID = 1L;
+
+    private String propertyName;
+    private Class theClass;
+    private transient Method method;
+
+    public GetterMethod(Class theClass, String propertyName) {
+      this.theClass = theClass;
+      this.propertyName = NamingUtil.getStaticPropertyName(theClass, propertyName);
+    }
+
+    @Override
+    @SuppressWarnings("unchecked")
+    public Method getMethod() {
+      if (method != null) {
+        return method;
+      }
+      Property property = ModelProvider.getInstance().getEntity(theClass).getProperty(propertyName);
+      String methodName = property.getGetterSetterName();
+      methodName = (property.isBoolean() ? "is" : "get") + methodName.substring(0, 1).toUpperCase()
+          + methodName.substring(1);
+      try {
+        method = theClass.getDeclaredMethod(methodName);
+      } catch (NoSuchMethodException | SecurityException e) {
+        log.debug("Could not find method {} of class {}", methodName, theClass.getName());
+      }
+      return method;
+    }
+
+    @Override
+    public Member getMember() {
+      return getMethod();
+    }
+
+    @Override
+    public String getMethodName() {
+      Method getter = getMethod();
+      if (getter == null) {
+        return null;
+      }
+      return getter.getName();
+    }
+
+    @Override
+    public Class getReturnType() {
+      Method getter = getMethod();
+      if (getter == null) {
+        return null;
+      }
+      return getter.getReturnType();
+    }
+
+    @Override
+    public Object get(Object owner) {
+      return ((BaseOBObject) owner).getValue(propertyName);
+    }
+
+    @Override
+    public Object getForInsert(Object owner, Map mergeMap, SharedSessionContractImplementor session) {
+      return get(owner);
+    }
+  }
+
+  private static class SetterMethod implements Setter {
+    private static final long serialVersionUID = 1L;
+    private static final String ID_SETTER = "setId";
+
+    private String propertyName;
+    private Class theClass;
+    private transient Method method;
+
+    public SetterMethod(Class theClass, String propertyName) {
+      this.theClass = theClass;
+      this.propertyName = NamingUtil.getStaticPropertyName(theClass, propertyName);
+    }
+
+    @Override
+    @SuppressWarnings("unchecked")
+    public Method getMethod() {
+      if (method != null) {
+        return method;
+      }
+      if (!BaseOBObject.ID.equals(propertyName)) {
+        return null;
+      }
+      try {
+        method = theClass.getDeclaredMethod(ID_SETTER, String.class);
+      } catch (NoSuchMethodException | SecurityException e) {
+        log.debug("Could not find method setId(String) method of class {}", theClass.getName());
+      }
+      return method;
+    }
+
+    @Override
+    public String getMethodName() {
+      Method setter = getMethod();
+      if (setter == null) {
+        return null;
+      }
+      return setter.getName();
+    }
+
+    @Override
+    public void set(Object target, Object value, SessionFactoryImplementor factory) {
+      ((BaseOBObject) target).setValue(propertyName, value);
+    }
+  }
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/org/openbravo/dal/core/DalPropertyAccessStrategy.java	Tue Jul 24 10:44:21 2018 +0200
@@ -0,0 +1,36 @@
+/*
+ *************************************************************************
+ * The contents of this file are subject to the Openbravo  Public  License
+ * Version  1.1  (the  "License"),  being   the  Mozilla   Public  License
+ * Version 1.1  with a permitted attribution clause; you may not  use this
+ * file except in compliance with the License. You  may  obtain  a copy of
+ * the License at http://www.openbravo.com/legal/license.html 
+ * Software distributed under the License  is  distributed  on  an "AS IS"
+ * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
+ * License for the specific  language  governing  rights  and  limitations
+ * 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 Rights Reserved. 
+ * Contributor(s):  ______________________________________.
+ ************************************************************************
+ */
+
+package org.openbravo.dal.core;
+
+import org.hibernate.property.access.spi.PropertyAccess;
+import org.hibernate.property.access.spi.PropertyAccessStrategy;
+
+/**
+ * This class is used as a factory class by the {@link DalMappingGenerator} to build the
+ * {@link DalPropertyAccess} instances during the mapping generation.
+ */
+public class DalPropertyAccessStrategy implements PropertyAccessStrategy {
+
+  @Override
+  @SuppressWarnings("rawtypes")
+  public PropertyAccess buildPropertyAccess(Class containerJavaType, String propertyName) {
+    return new DalPropertyAccess(this, containerJavaType, propertyName);
+  }
+}
--- a/src/org/openbravo/dal/core/DalSessionFactory.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/dal/core/DalSessionFactory.java	Tue Jul 24 10:44:21 2018 +0200
@@ -19,28 +19,37 @@
 
 package org.openbravo.dal.core;
 
-import java.io.Serializable;
 import java.sql.Connection;
 import java.sql.PreparedStatement;
+import java.util.List;
 import java.util.Map;
 import java.util.Properties;
 import java.util.Set;
 
 import javax.naming.NamingException;
 import javax.naming.Reference;
+import javax.persistence.EntityGraph;
+import javax.persistence.EntityManager;
+import javax.persistence.PersistenceUnitUtil;
+import javax.persistence.Query;
+import javax.persistence.SynchronizationType;
+import javax.persistence.criteria.CriteriaBuilder;
 
 import org.hibernate.Cache;
 import org.hibernate.HibernateException;
-import org.hibernate.Interceptor;
+import org.hibernate.Metamodel;
+import org.hibernate.Session;
+import org.hibernate.SessionBuilder;
 import org.hibernate.SessionFactory;
 import org.hibernate.StatelessSession;
+import org.hibernate.StatelessSessionBuilder;
 import org.hibernate.TypeHelper;
-import org.hibernate.classic.Session;
-import org.hibernate.connection.ConnectionProvider;
-import org.hibernate.engine.FilterDefinition;
-import org.hibernate.engine.SessionFactoryImplementor;
-import org.hibernate.engine.SessionImplementor;
-import org.hibernate.jdbc.BorrowedConnectionProxy;
+import org.hibernate.boot.spi.SessionFactoryOptions;
+import org.hibernate.engine.jdbc.connections.spi.JdbcConnectionAccess;
+import org.hibernate.engine.spi.FilterDefinition;
+import org.hibernate.engine.spi.SessionImplementor;
+import org.hibernate.internal.SessionFactoryImpl;
+import org.hibernate.internal.StatelessSessionImpl;
 import org.hibernate.metadata.ClassMetadata;
 import org.hibernate.metadata.CollectionMetadata;
 import org.hibernate.stat.Statistics;
@@ -62,6 +71,7 @@
   private static final long serialVersionUID = 1L;
 
   private SessionFactory delegateSessionFactory;
+  private JdbcConnectionAccess jdbcConnectionAccess;
 
   /**
    * NOTE: Openbravo requires normal application code to use the DalSessionFactory and not the real
@@ -81,38 +91,6 @@
     delegateSessionFactory.close();
   }
 
-  public void evict(Class persistentClass, Serializable id) throws HibernateException {
-    delegateSessionFactory.evict(persistentClass, id);
-  }
-
-  public void evict(Class persistentClass) throws HibernateException {
-    delegateSessionFactory.evict(persistentClass);
-  }
-
-  public void evictCollection(String roleName, Serializable id) throws HibernateException {
-    delegateSessionFactory.evictCollection(roleName, id);
-  }
-
-  public void evictCollection(String roleName) throws HibernateException {
-    delegateSessionFactory.evictCollection(roleName);
-  }
-
-  public void evictEntity(String entityName, Serializable id) throws HibernateException {
-    delegateSessionFactory.evictEntity(entityName, id);
-  }
-
-  public void evictEntity(String entityName) throws HibernateException {
-    delegateSessionFactory.evictEntity(entityName);
-  }
-
-  public void evictQueries() throws HibernateException {
-    delegateSessionFactory.evictQueries();
-  }
-
-  public void evictQueries(String cacheRegion) throws HibernateException {
-    delegateSessionFactory.evictQueries(cacheRegion);
-  }
-
   public Map getAllClassMetadata() throws HibernateException {
     return delegateSessionFactory.getAllClassMetadata();
   }
@@ -162,17 +140,9 @@
    */
   @Override
   public Session openSession() throws HibernateException {
-    // NOTE: workaround for this issue:
-    // http://opensource.atlassian.com/projects/hibernate/browse/HHH-3529
     final Session session = delegateSessionFactory.openSession();
-    final ClassLoader currentLoader = Thread.currentThread().getContextClassLoader();
-    try {
-      Thread.currentThread().setContextClassLoader(BorrowedConnectionProxy.class.getClassLoader());
-      Connection conn = ((SessionImplementor) session).connection();
-      initConnection(conn);
-    } finally {
-      Thread.currentThread().setContextClassLoader(currentLoader);
-    }
+    Connection conn = ((SessionImplementor) session).connection();
+    initConnection(conn);
     return session;
   }
 
@@ -191,40 +161,9 @@
    * Note method sets user session information in the database and opens a connection for this.
    */
   @Override
-  public Session openSession(Connection connection, Interceptor interceptor) {
-    // NOTE: workaround for this issue:
-    // http://opensource.atlassian.com/projects/hibernate/browse/HHH-3529
-    final Session session = delegateSessionFactory.openSession(connection, interceptor);
-    initializeDBSessionInfo((SessionImplementor) session);
-    return session;
-  }
-
-  /**
-   * Note method sets user session information in the database and opens a connection for this.
-   */
-  @Override
-  public Session openSession(Connection connection) {
-    // no need to initialize audit info for current connection: it's already done
-    return delegateSessionFactory.openSession(connection);
-  }
-
-  /**
-   * Note method sets user session information in the database and opens a connection for this.
-   */
-  @Override
-  public Session openSession(Interceptor interceptor) throws HibernateException {
-    final Session session = delegateSessionFactory.openSession(interceptor);
-    initializeDBSessionInfo((SessionImplementor) session);
-    return session;
-  }
-
-  /**
-   * Note method sets user session information in the database and opens a connection for this.
-   */
-  @Override
   public StatelessSession openStatelessSession() {
     final StatelessSession session = delegateSessionFactory.openStatelessSession();
-    initializeDBSessionInfo((SessionImplementor) session);
+    initializeDBSessionInfo((StatelessSessionImpl) session);
     return session;
   }
 
@@ -234,22 +173,14 @@
   @Override
   public StatelessSession openStatelessSession(Connection connection) {
     final StatelessSession session = delegateSessionFactory.openStatelessSession(connection);
-    initializeDBSessionInfo((SessionImplementor) session);
+    initializeDBSessionInfo((StatelessSessionImpl) session);
     return session;
   }
 
-  private void initializeDBSessionInfo(SessionImplementor session) {
-    // NOTE: workaround for this issue:
-    // http://opensource.atlassian.com/projects/hibernate/browse/HHH-3529
+  private void initializeDBSessionInfo(StatelessSessionImpl session) {
     Connection conn = session.connection();
-    final ClassLoader currentLoader = Thread.currentThread().getContextClassLoader();
-    try {
-      Thread.currentThread().setContextClassLoader(BorrowedConnectionProxy.class.getClassLoader());
-      SessionInfo.initDB(conn, OBPropertiesProvider.getInstance().getOpenbravoProperties()
-          .getProperty("bbdd.rdbms"));
-    } finally {
-      Thread.currentThread().setContextClassLoader(currentLoader);
-    }
+    SessionInfo.initDB(conn, OBPropertiesProvider.getInstance().getOpenbravoProperties()
+        .getProperty("bbdd.rdbms"));
   }
 
   public Cache getCache() {
@@ -264,7 +195,92 @@
     return delegateSessionFactory.getTypeHelper();
   }
 
-  public ConnectionProvider getConnectionProvider() {
-    return ((SessionFactoryImplementor) delegateSessionFactory).getConnectionProvider();
+  JdbcConnectionAccess getJdbcConnectionAccess() {
+    if (jdbcConnectionAccess == null) {
+      jdbcConnectionAccess = ((SessionFactoryImpl) delegateSessionFactory).getJdbcServices()
+          .getBootstrapJdbcConnectionAccess();
+    }
+    return jdbcConnectionAccess;
   }
+
+  @Override
+  public <T> void addNamedEntityGraph(String graphName, EntityGraph<T> entityGraph) {
+    delegateSessionFactory.addNamedEntityGraph(graphName, entityGraph);
+  }
+
+  @Override
+  public void addNamedQuery(String name, Query query) {
+    delegateSessionFactory.addNamedQuery(name, query);
+  }
+
+  @Override
+  public EntityManager createEntityManager() {
+    return delegateSessionFactory.createEntityManager();
+  }
+
+  @Override
+  public EntityManager createEntityManager(Map map) {
+    return delegateSessionFactory.createEntityManager(map);
+  }
+
+  @Override
+  public EntityManager createEntityManager(SynchronizationType synchronizationType) {
+    return delegateSessionFactory.createEntityManager(synchronizationType);
+  }
+
+  @Override
+  public EntityManager createEntityManager(SynchronizationType synchronizationType, Map map) {
+    return delegateSessionFactory.createEntityManager(synchronizationType, map);
+  }
+
+  @Override
+  public CriteriaBuilder getCriteriaBuilder() {
+    return delegateSessionFactory.getCriteriaBuilder();
+  }
+
+  @Override
+  public PersistenceUnitUtil getPersistenceUnitUtil() {
+    return delegateSessionFactory.getPersistenceUnitUtil();
+  }
+
+  @Override
+  public Map<String, Object> getProperties() {
+    return delegateSessionFactory.getProperties();
+  }
+
+  @Override
+  public boolean isOpen() {
+    return delegateSessionFactory.isOpen();
+  }
+
+  @Override
+  public <T> T unwrap(Class<T> clazz) {
+    return delegateSessionFactory.unwrap(clazz);
+  }
+
+  @Override
+  public <T> List<EntityGraph<? super T>> findEntityGraphsByType(Class<T> entityClass) {
+    return delegateSessionFactory.findEntityGraphsByType(entityClass);
+  }
+
+  @Override
+  public Metamodel getMetamodel() {
+    return delegateSessionFactory.getMetamodel();
+  }
+
+  @Override
+  public SessionFactoryOptions getSessionFactoryOptions() {
+    return delegateSessionFactory.getSessionFactoryOptions();
+  }
+
+  @Override
+  public SessionBuilder withOptions() {
+    return delegateSessionFactory.withOptions();
+  }
+
+  @Override
+  public StatelessSessionBuilder withStatelessOptions() {
+    return delegateSessionFactory.withStatelessOptions();
+  }
+
 }
--- a/src/org/openbravo/dal/core/DalSessionFactoryController.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/dal/core/DalSessionFactoryController.java	Tue Jul 24 10:44:21 2018 +0200
@@ -19,6 +19,9 @@
 
 package org.openbravo.dal.core;
 
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
 import java.util.HashMap;
 import java.util.Map;
 
@@ -26,11 +29,13 @@
 import javax.enterprise.inject.Instance;
 import javax.inject.Inject;
 
-import org.apache.log4j.Logger;
 import org.hibernate.cfg.Configuration;
 import org.hibernate.dialect.function.SQLFunction;
+import org.openbravo.base.exception.OBException;
 import org.openbravo.base.model.ModelProvider;
 import org.openbravo.base.session.SessionFactoryController;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 /**
  * Initializes and provides the session factory for the runtime dal layer. This
@@ -42,7 +47,7 @@
  */
 
 public class DalSessionFactoryController extends SessionFactoryController {
-  private static final Logger log = Logger.getLogger(DalSessionFactoryController.class);
+  private static final Logger log = LoggerFactory.getLogger(DalSessionFactoryController.class);
 
   @Inject
   @Any
@@ -52,10 +57,31 @@
 
   @Override
   protected void mapModel(Configuration configuration) {
-    final String mapping = DalMappingGenerator.getInstance().generateMapping();
-    log.debug("Generated mapping: ");
-    log.debug(mapping);
-    configuration.addXML(mapping);
+    DalMappingGenerator mappingGenerator = DalMappingGenerator.getInstance();
+    final String mapping = mappingGenerator.generateMapping();
+    log.debug("Generated mapping: \n{}", mapping);
+
+    if (mappingGenerator.getHibernateFileLocation() != null) {
+      configuration.addFile(mappingGenerator.getHibernateFileLocation());
+      return;
+    }
+
+    Path tmpFile = null;
+    try {
+      tmpFile = Files.createTempFile("", ".hbm");
+      Files.write(tmpFile, mapping.getBytes());
+      configuration.addFile(tmpFile.toString());
+    } catch (IOException ioex) {
+      throw new OBException("Error writing temporary .hbm file for configuration", ioex);
+    } finally {
+      try {
+        if (tmpFile != null) {
+          Files.delete(tmpFile);
+        }
+      } catch (IOException ioex) {
+        log.error("Error deleting temporary .hbm file for configuration", ioex);
+      }
+    }
   }
 
   @Override
--- a/src/org/openbravo/dal/core/OBContext.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/dal/core/OBContext.java	Tue Jul 24 10:44:21 2018 +0200
@@ -37,7 +37,7 @@
 
 import org.apache.log4j.Logger;
 import org.hibernate.Hibernate;
-import org.hibernate.Query;
+import org.hibernate.query.Query;
 import org.openbravo.base.exception.OBSecurityException;
 import org.openbravo.base.provider.OBNotSingleton;
 import org.openbravo.base.provider.OBProvider;
@@ -651,20 +651,19 @@
       Set<String> additionalOrgs, boolean isActiveOrganization) {
 
     if (orgList != null) {
-      return new ArrayList<String>(orgList);
+      return new ArrayList<>(orgList);
     }
 
-    String propertyActive = isActiveOrganization ? "Y" : "N";
-    final Query qry = SessionHandler.getInstance().createQuery(
+    final Query<String> qry = SessionHandler.getInstance().createQuery(
         "select o.id from " + Organization.class.getName() + " o, "
             + RoleOrganization.class.getName() + " roa where o." + Organization.PROPERTY_ID
             + "=roa." + RoleOrganization.PROPERTY_ORGANIZATION + "." + Organization.PROPERTY_ID
             + " and roa." + RoleOrganization.PROPERTY_ROLE + "." + Organization.PROPERTY_ID
             + "= :targetRoleId" + " and roa." + RoleOrganization.PROPERTY_ACTIVE + "='Y' and o."
-            + Organization.PROPERTY_ACTIVE + "= :active");
-    qry.setString("targetRoleId", targetRole.getId());
-    qry.setString("active", propertyActive);
-    @SuppressWarnings("unchecked")
+            + Organization.PROPERTY_ACTIVE + "= :active", String.class);
+    qry.setParameter("targetRoleId", targetRole.getId());
+    qry.setParameter("active", isActiveOrganization);
+
     List<String> currentOrgList = qry.list();
 
     if (additionalOrgs != null) {
@@ -674,15 +673,14 @@
         }
       }
     }
-    return new ArrayList<String>(currentOrgList);
+    return new ArrayList<>(currentOrgList);
   }
 
-  @SuppressWarnings("unchecked")
   private List<String> getOrganizations(Client client) {
-    final Query qry = SessionHandler.getInstance().createQuery(
+    final Query<String> qry = SessionHandler.getInstance().createQuery(
         "select o.id from " + Organization.class.getName() + " o where " + "o."
             + Organization.PROPERTY_CLIENT + "=:client and o." + Organization.PROPERTY_ACTIVE
-            + "='Y'");
+            + "='Y'", String.class);
     qry.setParameter("client", client);
     organizationList = qry.list();
     return organizationList;
@@ -982,14 +980,15 @@
       Check.isTrue(getCurrentClient().isActive(), "Current Client " + getCurrentClient().getName()
           + " is not active!");
       if (languageCode != null) {
-        final Query qry = SessionHandler.getInstance().createQuery(
+        final Query<Language> qry = SessionHandler.getInstance().createQuery(
             "select l from " + Language.class.getName() + " l where l."
-                + Language.PROPERTY_LANGUAGE + "=:languageCode ");
+                + Language.PROPERTY_LANGUAGE + "=:languageCode ", Language.class);
         qry.setParameter("languageCode", languageCode);
-        if (qry.list().isEmpty()) {
+        List<Language> languages = qry.list();
+        if (languages.isEmpty()) {
           throw new IllegalArgumentException("No language found for code " + languageCode);
         }
-        setLanguage((Language) qry.list().get(0));
+        setLanguage(languages.get(0));
       } else if (getUser().getDefaultLanguage() != null
           && getUser().getDefaultLanguage().isActive()) {
         setLanguage(getUser().getDefaultLanguage());
@@ -1003,23 +1002,23 @@
 
       Check.isNotNull(getLanguage(), "Language may not be null");
 
-      final Query trl = SessionHandler.getInstance().createQuery(
+      final Query<Long> trl = SessionHandler.getInstance().createQuery(
           "select count(*) from " + Language.class.getName() + " l where l."
-              + Language.PROPERTY_SYSTEMLANGUAGE + "= true ");
+              + Language.PROPERTY_SYSTEMLANGUAGE + "= true ", Long.class);
 
       // There are translations installed in the system when there are more than one system
       // language. There's always at last one which is the base language.
-      setTranslationInstalled(((Long) trl.list().get(0)) > 1);
+      setTranslationInstalled(trl.list().get(0) > 1);
 
       setReadableClients(role);
 
       // note sometimes the warehouseId is an empty string
       // this happens when it is set from the session variables
       if (warehouseId != null && warehouseId.trim().length() > 0) {
-        final Query qry = SessionHandler.getInstance().createQuery(
-            "select w from " + Warehouse.class.getName() + " w where w.id=:id");
+        final Query<Warehouse> qry = SessionHandler.getInstance().createQuery(
+            "select w from " + Warehouse.class.getName() + " w where w.id=:id", Warehouse.class);
         qry.setParameter("id", warehouseId);
-        setWarehouse((Warehouse) qry.list().get(0));
+        setWarehouse(qry.uniqueResult());
       } else if (getUser().getDefaultWarehouse() != null) {
         setWarehouse(getUser().getDefaultWarehouse());
       }
@@ -1048,21 +1047,20 @@
     return true;
   }
 
-  @SuppressWarnings({ "unchecked" })
   private <T extends Object> T getOne(Class<T> clz, String qryStr, Map<String, String> parameters,
       boolean doCheck) {
-    final Query qry = SessionHandler.getInstance().createQuery(qryStr);
+    final Query<T> qry = SessionHandler.getInstance().createQuery(qryStr, clz);
     qry.setProperties(parameters);
     qry.setMaxResults(1);
-    final List<?> result = qry.list();
+    final List<T> result = qry.list();
     if (doCheck && result.size() != 1) {
       log.error("The query '" + qryStr + "' returned " + result.size()
           + " results while only 1 result was expected");
     }
-    if (result.size() == 0) {
+    if (result.isEmpty()) {
       return null;
     }
-    return (T) result.get(0);
+    return result.get(0);
   }
 
   public User getUser() {
--- a/src/org/openbravo/dal/core/OBDynamicPropertyHandler.java	Tue Jul 24 10:39:37 2018 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,133 +0,0 @@
-/*
- *************************************************************************
- * The contents of this file are subject to the Openbravo  Public  License
- * Version  1.1  (the  "License"),  being   the  Mozilla   Public  License
- * Version 1.1  with a permitted attribution clause; you may not  use this
- * file except in compliance with the License. You  may  obtain  a copy of
- * the License at http://www.openbravo.com/legal/license.html 
- * Software distributed under the License  is  distributed  on  an "AS IS"
- * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
- * License for the specific  language  governing  rights  and  limitations
- * 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-2016 Openbravo SLU 
- * All Rights Reserved. 
- * Contributor(s):  ______________________________________.
- ************************************************************************
- */
-
-package org.openbravo.dal.core;
-
-import java.lang.reflect.Member;
-import java.lang.reflect.Method;
-import java.util.Map;
-
-import org.hibernate.HibernateException;
-import org.hibernate.PropertyNotFoundException;
-import org.hibernate.engine.SessionFactoryImplementor;
-import org.hibernate.engine.SessionImplementor;
-import org.hibernate.property.PropertyAccessor;
-import org.openbravo.base.model.NamingUtil;
-import org.openbravo.base.structure.BaseOBObject;
-
-/**
- * The hibernate getter/setter for a dynamic property.
- * 
- * @author mtaal
- */
-@SuppressWarnings("rawtypes")
-public class OBDynamicPropertyHandler implements PropertyAccessor {
-  public Getter getGetter(Class theClass, String propertyName) throws PropertyNotFoundException {
-    return new Getter(theClass, propertyName);
-  }
-
-  public Setter getSetter(Class theClass, String propertyName) throws PropertyNotFoundException {
-    return new Setter(theClass, propertyName);
-  }
-
-  public static class Getter implements org.hibernate.property.Getter {
-    private static final long serialVersionUID = 1L;
-    private static final String ID_GETTER = "getId";
-
-    private String propertyName;
-    private Class theClass;
-
-    public Getter(Class theClass, String propertyName) {
-      this.theClass = theClass;
-      this.propertyName = NamingUtil.getStaticPropertyName(theClass, propertyName);
-    }
-
-    @SuppressWarnings("unchecked")
-    public Method getMethod() {
-      // special case for IDs, so when executing getId() in a proxy, it is not necessary to load the
-      // whole object from DB
-      if (BaseOBObject.ID.equals(propertyName)) {
-        try {
-          return theClass.getDeclaredMethod(ID_GETTER);
-        } catch (NoSuchMethodException e) {
-        } catch (SecurityException e) {
-        }
-      }
-
-      return null;
-    }
-
-    public Member getMember() {
-      return null;
-    }
-
-    public String getMethodName() {
-      return null;
-    }
-
-    public Object get(Object owner) throws HibernateException {
-      return ((BaseOBObject) owner).getValue(propertyName);
-    }
-
-    public Object getForInsert(Object owner, Map mergeMap, SessionImplementor session)
-        throws HibernateException {
-      return get(owner);
-    }
-
-    public Class getReturnType() {
-      return null;
-    }
-  }
-
-  public static class Setter implements org.hibernate.property.Setter {
-    private static final long serialVersionUID = 1L;
-    private static final String ID_SETTER = "setId";
-
-    private String propertyName;
-    private Class theClass;
-
-    public Setter(Class theClass, String propertyName) {
-      this.theClass = theClass;
-      this.propertyName = NamingUtil.getStaticPropertyName(theClass, propertyName);
-    }
-
-    @SuppressWarnings("unchecked")
-    public Method getMethod() {
-      if (BaseOBObject.ID.equals(propertyName)) {
-        try {
-          return theClass.getDeclaredMethod(ID_SETTER, String.class);
-        } catch (NoSuchMethodException e) {
-        } catch (SecurityException e) {
-        }
-      }
-
-      return null;
-    }
-
-    public String getMethodName() {
-      return null;
-    }
-
-    public void set(Object target, Object value, SessionFactoryImplementor factory)
-        throws HibernateException {
-      ((BaseOBObject) target).setValue(propertyName, value);
-    }
-
-  }
-}
--- a/src/org/openbravo/dal/core/OBDynamicTuplizer.java	Tue Jul 24 10:39:37 2018 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,131 +0,0 @@
-/*
- *************************************************************************
- * The contents of this file are subject to the Openbravo  Public  License
- * Version  1.1  (the  "License"),  being   the  Mozilla   Public  License
- * Version 1.1  with a permitted attribution clause; you may not  use this
- * file except in compliance with the License. You  may  obtain  a copy of
- * the License at http://www.openbravo.com/legal/license.html 
- * Software distributed under the License  is  distributed  on  an "AS IS"
- * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
- * License for the specific  language  governing  rights  and  limitations
- * 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-2011 Openbravo SLU 
- * All Rights Reserved. 
- * Contributor(s):  ______________________________________.
- ************************************************************************
- */
-
-package org.openbravo.dal.core;
-
-import org.apache.log4j.Logger;
-import org.hibernate.EntityMode;
-import org.hibernate.EntityNameResolver;
-import org.hibernate.HibernateException;
-import org.hibernate.engine.SessionFactoryImplementor;
-import org.hibernate.mapping.PersistentClass;
-import org.hibernate.mapping.Property;
-import org.hibernate.property.Getter;
-import org.hibernate.property.Setter;
-import org.hibernate.proxy.ProxyFactory;
-import org.hibernate.proxy.map.MapProxyFactory;
-import org.hibernate.tuple.Instantiator;
-import org.hibernate.tuple.entity.AbstractEntityTuplizer;
-import org.hibernate.tuple.entity.EntityMetamodel;
-import org.openbravo.base.structure.BaseOBObject;
-import org.openbravo.base.structure.DynamicOBObject;
-
-/**
- * The tuplizer for {@link DynamicOBObject} objects. This is class used by Hibernate. It sets the
- * object instantiator (the factory) used by Hibernate.
- * 
- * @see OBInstantiator
- * @author mtaal
- */
-public class OBDynamicTuplizer extends AbstractEntityTuplizer {
-  private static final Logger log = Logger.getLogger(OBDynamicTuplizer.class);
-
-  private final PersistentClass persistentClass;
-
-  public OBDynamicTuplizer(EntityMetamodel entityMetamodel, PersistentClass mappedEntity) {
-    super(entityMetamodel, mappedEntity);
-    log.debug("Created tuplizer for "
-        + (mappedEntity.getMappedClass() != null ? mappedEntity.getMappedClass().getName()
-            : mappedEntity.getEntityName()));
-    persistentClass = mappedEntity;
-  }
-
-  // this is done in the generated mapping
-  // @Override
-  // protected Getter buildPropertyGetter(Property mappedProperty,
-  // PersistentClass mappedEntity) {
-  // return new OBDynamicPropertyHandler.Getter(mappedProperty.getName());
-  // }
-  //
-  // @Override
-  // protected Setter buildPropertySetter(Property mappedProperty,
-  // PersistentClass mappedEntity) {
-  // return new OBDynamicPropertyHandler.Setter(mappedProperty.getName());
-  // }
-
-  @Override
-  public String determineConcreteSubclassEntityName(Object entityInstance,
-      SessionFactoryImplementor factory) {
-    BaseOBObject bob = (BaseOBObject) entityInstance;
-    return bob.getEntity().getName();
-  }
-
-  @Override
-  public EntityNameResolver[] getEntityNameResolvers() {
-    return null;
-  }
-
-  @Override
-  protected Instantiator buildInstantiator(PersistentClass mappingInfo) {
-    return new OBInstantiator(mappingInfo);
-  }
-
-  @Override
-  protected ProxyFactory buildProxyFactory(PersistentClass thePersistentClass, Getter idGetter,
-      Setter idSetter) {
-    ProxyFactory pf = new MapProxyFactory();
-    try {
-      pf.postInstantiate(getEntityName(), null, null, null, null, null);
-    } catch (final HibernateException he) {
-      log.warn("could not create proxy factory for:" + getEntityName(), he);
-      pf = null;
-    }
-    return pf;
-  }
-
-  @SuppressWarnings("rawtypes")
-  public Class getMappedClass() {
-    return persistentClass.getMappedClass();
-  }
-
-  @SuppressWarnings("rawtypes")
-  public Class getConcreteProxyClass() {
-    return persistentClass.getMappedClass();
-  }
-
-  @Override
-  public EntityMode getEntityMode() {
-    return EntityMode.POJO;
-  }
-
-  @Override
-  protected Getter buildPropertyGetter(Property mappedProperty, PersistentClass mappedEntity) {
-    return mappedProperty.getGetter(mappedEntity.getMappedClass());
-  }
-
-  @Override
-  protected Setter buildPropertySetter(Property mappedProperty, PersistentClass mappedEntity) {
-    return mappedProperty.getSetter(mappedEntity.getMappedClass());
-  }
-
-  public boolean isInstrumented() {
-    return false;
-  }
-
-}
\ No newline at end of file
--- a/src/org/openbravo/dal/core/OBInterceptor.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/dal/core/OBInterceptor.java	Tue Jul 24 10:44:21 2018 +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-2017 Openbravo SLU 
+ * All portions are Copyright (C) 2008-2018 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -483,4 +483,15 @@
     super.preFlush(entities);
   }
 
+  // allow Hibernate to determine that the object is a valid entity
+  // this is needed to avoid throwing an exception when evicting an already evicted BaseOBObject
+  @Override
+  public String getEntityName(Object entity) {
+    if (!(entity instanceof BaseOBObject)) {
+      return null;
+    }
+    BaseOBObject bob = (BaseOBObject) entity;
+    return bob.getEntityName();
+  }
+
 }
\ No newline at end of file
--- a/src/org/openbravo/dal/core/OBTuplizer.java	Tue Jul 24 10:39:37 2018 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,145 +0,0 @@
-/*
- *************************************************************************
- * The contents of this file are subject to the Openbravo  Public  License
- * Version  1.1  (the  "License"),  being   the  Mozilla   Public  License
- * Version 1.1  with a permitted attribution clause; you may not  use this
- * file except in compliance with the License. You  may  obtain  a copy of
- * the License at http://www.openbravo.com/legal/license.html 
- * Software distributed under the License  is  distributed  on  an "AS IS"
- * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
- * License for the specific  language  governing  rights  and  limitations
- * 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-2012 Openbravo SLU 
- * All Rights Reserved. 
- * Contributor(s):  ______________________________________.
- ************************************************************************
- */
-
-package org.openbravo.dal.core;
-
-import java.lang.reflect.Method;
-import java.util.HashSet;
-import java.util.Iterator;
-
-import org.apache.log4j.Logger;
-import org.hibernate.HibernateException;
-import org.hibernate.MappingException;
-import org.hibernate.mapping.PersistentClass;
-import org.hibernate.mapping.Subclass;
-import org.hibernate.property.Getter;
-import org.hibernate.property.Setter;
-import org.hibernate.proxy.HibernateProxy;
-import org.hibernate.proxy.ProxyFactory;
-import org.hibernate.tuple.Instantiator;
-import org.hibernate.tuple.entity.EntityMetamodel;
-import org.hibernate.tuple.entity.PojoEntityTuplizer;
-import org.hibernate.type.CompositeType;
-import org.hibernate.util.ReflectHelper;
-import org.openbravo.base.util.Check;
-
-/**
- * The tuplizer for OBObjects objects. This is class used by Hibernate. It sets the object
- * instantiator (the factory) used by Hibernate.
- * 
- * @see OBInstantiator
- * @author mtaal
- */
-public class OBTuplizer extends PojoEntityTuplizer {
-  private static final Logger log = Logger.getLogger(OBTuplizer.class);
-
-  public OBTuplizer(EntityMetamodel entityMetamodel, PersistentClass mappedEntity) {
-    super(entityMetamodel, mappedEntity);
-    log.debug("Created tuplizer for "
-        + (mappedEntity.getMappedClass() != null ? mappedEntity.getMappedClass().getName()
-            : mappedEntity.getEntityName()));
-  }
-
-  // this is done in the generated mapping
-  // @Override
-  // protected Getter buildPropertyGetter(Property mappedProperty,
-  // PersistentClass mappedEntity) {
-  // return new OBDynamicPropertyHandler.Getter(mappedProperty.getName());
-  // }
-  //
-  // @Override
-  // protected Setter buildPropertySetter(Property mappedProperty,
-  // PersistentClass mappedEntity) {
-  // return new OBDynamicPropertyHandler.Setter(mappedProperty.getName());
-  // }
-
-  @Override
-  protected Instantiator buildInstantiator(PersistentClass mappingInfo) {
-    return new OBInstantiator(mappingInfo);
-  }
-
-  @Override
-  protected ProxyFactory buildProxyFactory(PersistentClass thePersistentClass, Getter idGetter,
-      Setter idSetter) {
-    final Class<?> mappedClass = thePersistentClass.getMappedClass();
-    Check.isNotNull(mappedClass, "Mapped class of entity " + thePersistentClass.getEntityName()
-        + " is null");
-
-    // determine the id getter and setter methods from the proxy interface
-    // (if
-    // any)
-    // determine all interfaces needed by the resulting proxy
-    final HashSet<Object> proxyInterfaces = new HashSet<Object>();
-    proxyInterfaces.add(HibernateProxy.class);
-
-    final Class<?> proxyInterface = thePersistentClass.getProxyInterface();
-
-    if (proxyInterface != null && !mappedClass.equals(proxyInterface)) {
-      if (!proxyInterface.isInterface()) {
-        throw new MappingException("proxy must be either an interface, or the class itself: "
-            + getEntityName());
-      }
-      proxyInterfaces.add(proxyInterface);
-    }
-
-    if (mappedClass.isInterface()) {
-      proxyInterfaces.add(mappedClass);
-    }
-
-    final Iterator<?> iter = thePersistentClass.getSubclassIterator();
-    while (iter.hasNext()) {
-      final Subclass subclass = (Subclass) iter.next();
-      final Class<?> subclassProxy = subclass.getProxyInterface();
-      final Class<?> subclassClass = subclass.getMappedClass();
-      if (subclassProxy != null && !subclassClass.equals(subclassProxy)) {
-        if (proxyInterface == null || !proxyInterface.isInterface()) {
-          throw new MappingException("proxy must be either an interface, or the class itself: "
-              + subclass.getEntityName());
-        }
-        proxyInterfaces.add(subclassProxy);
-      }
-    }
-
-    final Method idGetterMethod = idGetter == null ? null : idGetter.getMethod();
-    final Method idSetterMethod = idSetter == null ? null : idSetter.getMethod();
-
-    final Method proxyGetIdentifierMethod = idGetterMethod == null || proxyInterface == null ? null
-        : ReflectHelper.getMethod(proxyInterface, idGetterMethod);
-    final Method proxySetIdentifierMethod = idSetterMethod == null || proxyInterface == null ? null
-        : ReflectHelper.getMethod(proxyInterface, idSetterMethod);
-
-    ProxyFactory pf = buildProxyFactoryInternal(thePersistentClass, idGetter, idSetter);
-    try {
-      pf.postInstantiate(getEntityName(), mappedClass, proxyInterfaces, proxyGetIdentifierMethod,
-          proxySetIdentifierMethod,
-          thePersistentClass.hasEmbeddedIdentifier() ? (CompositeType) thePersistentClass
-              .getIdentifier().getType() : null);
-    } catch (final HibernateException he) {
-      log.warn("could not create proxy factory for:" + getEntityName(), he);
-      pf = null;
-    }
-    return pf;
-  }
-
-  @Override
-  public Class<?> getConcreteProxyClass() {
-    return getMappedClass();
-  }
-
-}
\ No newline at end of file
--- a/src/org/openbravo/dal/core/SessionHandler.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/dal/core/SessionHandler.java	Tue Jul 24 10:44:21 2018 +0200
@@ -31,10 +31,10 @@
 
 import org.apache.log4j.Logger;
 import org.hibernate.FlushMode;
-import org.hibernate.Query;
 import org.hibernate.Session;
 import org.hibernate.SessionFactory;
 import org.hibernate.Transaction;
+import org.hibernate.query.Query;
 import org.openbravo.base.exception.OBException;
 import org.openbravo.base.model.Entity;
 import org.openbravo.base.provider.OBNotSingleton;
@@ -241,7 +241,7 @@
       // If the connection has been obtained using an external connection pool it is passed to
       // openSession, to prevent a new connection to be created using the Hibernate default
       // connection pool
-      return sf.openSession(connection);
+      return sf.withOptions().connection(connection).openSession();
     } else {
       return sf.openSession();
     }
@@ -306,7 +306,7 @@
       // getting connection from Hibernate pool
       DalSessionFactory sf = (DalSessionFactory) SessionFactoryController.getInstance()
           .getSessionFactory();
-      newConnection = sf.getConnectionProvider().getConnection();
+      newConnection = sf.getJdbcConnectionAccess().obtainConnection();
       sf.initConnection(newConnection);
     }
     return newConnection;
@@ -537,14 +537,28 @@
    * 
    * @param qryStr
    *          the HQL query
+   * @param clazz
+   *          the class of the query's resulting objects
    * @return a new Query object
    */
-  public Query createQuery(String qryStr) {
-    return createQuery(DEFAULT_POOL, qryStr);
+  public <T> Query<T> createQuery(String qryStr, Class<T> clazz) {
+    return createQuery(DEFAULT_POOL, qryStr, clazz);
   }
 
-  private Query createQuery(String pool, String qryStr) {
-    return getSession(pool).createQuery(qryStr);
+  /**
+   * Create a query object from the current getSession().
+   * 
+   * @param qryStr
+   *          the HQL query
+   * @return a new Query object
+   */
+  @SuppressWarnings("unchecked")
+  public <T extends Object> Query<T> createQuery(String qryStr) {
+    return (Query<T>) createQuery(DEFAULT_POOL, qryStr, Object.class);
+  }
+
+  private <T> Query<T> createQuery(String pool, String qryStr, Class<T> clazz) {
+    return getSession(pool).createQuery(qryStr, clazz);
   }
 
   /**
@@ -557,7 +571,7 @@
   private void begin(String pool) {
     Check.isTrue(sessions.get(pool) == null, "Session must be null before begin");
     setSession(pool, createSession(pool));
-    getSession(pool).setFlushMode(FlushMode.COMMIT);
+    getSession(pool).setHibernateFlushMode(FlushMode.COMMIT);
     Check.isTrue(getTransaction(pool) == null, "tx must be null before begin");
     setTransaction(pool, getSession(pool).beginTransaction());
     setAvailablePool(pool);
--- a/src/org/openbravo/dal/security/AcctSchemaStructureProvider.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/dal/security/AcctSchemaStructureProvider.java	Tue Jul 24 10:44:21 2018 +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) 2016 Openbravo SLU 
+ * All portions are Copyright (C) 2016-2018 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -19,12 +19,11 @@
 
 package org.openbravo.dal.security;
 
-import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 
-import org.hibernate.Query;
+import org.hibernate.query.Query;
 import org.openbravo.base.provider.OBNotSingleton;
 import org.openbravo.dal.core.OBContext;
 import org.openbravo.dal.service.OBDal;
@@ -58,8 +57,7 @@
     acctSchemaByOrg.put(orgId, getAcctSchemasFromDB(orgId, clientID));
   }
 
-  @SuppressWarnings("unchecked")
-  private ArrayList<String> getAcctSchemasFromDB(String orgId, String clientID) {
+  private List<String> getAcctSchemasFromDB(String orgId, String clientID) {
     try {
       OBContext.setAdminMode(true);
       String where = " select a.id"
@@ -69,10 +67,10 @@
           + " and (ad_isorgincluded(:orgId, oas.organization.id, oas.client.id) <> -1 or :orgId = '0')"
           + " and a.active = true" + " and oas.active = true" + " group by a.id";
 
-      final Query qry = OBDal.getInstance().getSession().createQuery(where);
+      final Query<String> qry = OBDal.getInstance().getSession().createQuery(where, String.class);
       qry.setParameter("clientId", clientID);
       qry.setParameter("orgId", orgId);
-      return (ArrayList<String>) qry.list();
+      return qry.list();
     } finally {
       OBContext.restorePreviousMode();
     }
--- a/src/org/openbravo/dal/security/EntityAccessChecker.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/dal/security/EntityAccessChecker.java	Tue Jul 24 10:44:21 2018 +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-2017 Openbravo SLU 
+ * All portions are Copyright (C) 2008-2018 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -26,7 +26,7 @@
 import java.util.Set;
 
 import org.apache.log4j.Logger;
-import org.hibernate.Query;
+import org.hibernate.query.Query;
 import org.openbravo.base.exception.OBSecurityException;
 import org.openbravo.base.model.Entity;
 import org.openbravo.base.model.ModelProvider;
@@ -154,33 +154,36 @@
    * 
    * The static block only gets called once, when the class itself is initialized.
    */
-  @SuppressWarnings("unchecked")
   public static void calculateCachedElements() {
     String hqlQry = "select distinct(s.table.id), c.table.id from OBUISEL_Selector s "
         + "left join s.reference r left join r.aDColumnReferenceSearchKeyList c "
         + "where r.parentReference='" + SEARCH_REFERENCE + "'";
-    targetTablesIds = SessionHandler.getInstance().createQuery(hqlQry).list();
+    targetTablesIds = SessionHandler.getInstance().createQuery(hqlQry, Object[].class).list();
 
     hqlQry = "select p.id, c.table.id from ADColumn c inner join c.table t inner join "
         + "c.referenceSearchKey r inner join r.oBUISELSelectorList s inner join s.processDefintion "
         + "p  where r.parentReference='" + SELECTOR_REFERENCE + "'";
-    processAccessSelectors = SessionHandler.getInstance().createQuery(hqlQry).list();
+    processAccessSelectors = SessionHandler.getInstance().createQuery(hqlQry, Object[].class)
+        .list();
 
     hqlQry = "select p.id, c.table.id from ADColumn c inner join c.table t inner join "
         + "c.oBUIAPPProcess p";
-    processAccessButtons = SessionHandler.getInstance().createQuery(hqlQry).list();
+    processAccessButtons = SessionHandler.getInstance().createQuery(hqlQry, Object[].class).list();
 
     hqlQry = "select t.table.id, p.obuiappProcess.id, t.id from OBUIAPP_Parameter p inner join p.referenceSearchKey r inner join r.oBUIAPPRefWindowList rw inner join rw.window w inner join w.aDTabList t where p.reference.id in ('"
         + WINDOW_REFERENCE + "')";
-    parameterOfWindowProcessReference = SessionHandler.getInstance().createQuery(hqlQry).list();
+    parameterOfWindowProcessReference = SessionHandler.getInstance()
+        .createQuery(hqlQry, Object[].class).list();
 
     hqlQry = "select s.table.id, p.obuiappProcess.id from OBUIAPP_Parameter p inner join p.referenceSearchKey r inner join r.oBUISELSelectorList s where p.reference.id in('"
         + SELECTOR_REFERENCE + "','" + MULTI_SELECTOR_REFERENCE + "')";
-    parameterOfSelectorProcessReference = SessionHandler.getInstance().createQuery(hqlQry).list();
+    parameterOfSelectorProcessReference = SessionHandler.getInstance()
+        .createQuery(hqlQry, Object[].class).list();
 
     hqlQry = "select f.tab.table.id, f.tab.id from ADField f inner join f.column c inner join c.referenceSearchKey r  where r.parentReference='"
         + SELECTOR_REFERENCE + "'";
-    selectorsFromWindowReferences = SessionHandler.getInstance().createQuery(hqlQry).list();
+    selectorsFromWindowReferences = SessionHandler.getInstance()
+        .createQuery(hqlQry, Object[].class).list();
   }
 
   /**
@@ -202,13 +205,11 @@
       final String qryStr = "select t.table.id, wa.editableField from " + Tab.class.getName()
           + " t left join t.window w left join w.aDWindowAccessList wa"
           + " where wa.role.id= :roleId";
-      final Query qry = SessionHandler.getInstance().createQuery(qryStr);
+      final Query<Object[]> qry = SessionHandler.getInstance().createQuery(qryStr, Object[].class);
       qry.setParameter("roleId", getRoleId());
-      @SuppressWarnings("unchecked")
-      final List<Object> tabData = qry.list();
-      for (final Object o : tabData) {
-        final Object[] os = (Object[]) o;
+      final List<Object[]> tabData = qry.list();
 
+      for (final Object[] os : tabData) {
         final String tableId = (String) os[0];
         final Entity e = mp.getEntityByTableId(tableId);
         if (e == null) { // happens for AD_Client_Info and views
@@ -232,9 +233,10 @@
       // and take into account table access
       final String tafQryStr = "select ta from " + TableAccess.class.getName()
           + " ta where role.id= :roleId";
-      Query tafQry = SessionHandler.getInstance().createQuery(tafQryStr);
-      tafQry.setString("roleId", getRoleId());
-      @SuppressWarnings("unchecked")
+      Query<TableAccess> tafQry = SessionHandler.getInstance().createQuery(tafQryStr,
+          TableAccess.class);
+      tafQry.setParameter("roleId", getRoleId());
+
       final List<TableAccess> tas = tafQry.list();
       for (final TableAccess ta : tas) {
         final String tableName = ta.getTable().getName();
@@ -271,13 +273,13 @@
 
       // and take into account derived entities from process definition
       // union of writableEntities and readableEntities
-      List<Entity> processEntities = new ArrayList<Entity>(writableEntities);
+      List<Entity> processEntities = new ArrayList<>(writableEntities);
       for (final Entity readableEntity : readableEntities) {
         if (!processEntities.contains(readableEntity)) {
           processEntities.add(readableEntity);
         }
       }
-      if (processEntities.size() > 0) {
+      if (!processEntities.isEmpty()) {
         Set<String> processTables = new HashSet<>();
         for (final Entity entity : processEntities) {
           Table table = mp.getTableWithoutCheck(entity.getTableName());
@@ -307,10 +309,10 @@
       // and take into account explicit process access
       final String processAccessQryStr = "select p.obuiappProcess.id from "
           + ProcessAccess.class.getName() + " p where p.role.id= :roleId";
-      Query processAccessQry = SessionHandler.getInstance()
-          .createQuery(processAccessQryStr);
-      processAccessQry.setString("roleId", getRoleId());
-      @SuppressWarnings("unchecked")
+      Query<String> processAccessQry = SessionHandler.getInstance().createQuery(
+          processAccessQryStr, String.class);
+      processAccessQry.setParameter("roleId", getRoleId());
+
       final List<String> processAccessQuery = processAccessQry.list();
       for (final String processAccess : processAccessQuery) {
         processes.add(processAccess);
--- a/src/org/openbravo/dal/security/OrganizationStructureProvider.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/dal/security/OrganizationStructureProvider.java	Tue Jul 24 10:44:21 2018 +0200
@@ -29,7 +29,7 @@
 import java.util.Objects;
 import java.util.Set;
 
-import org.hibernate.SQLQuery;
+import org.hibernate.query.NativeQuery;
 import org.openbravo.base.provider.OBNotSingleton;
 import org.openbravo.base.util.Check;
 import org.openbravo.dal.core.OBContext;
@@ -89,7 +89,8 @@
         + "   and t.ad_table_id = '155'"
         + "   and t.ad_client_id = :clientId";
 
-    SQLQuery qry = OBDal.getInstance().getSession().createSQLQuery(sql);
+    @SuppressWarnings("rawtypes")
+    NativeQuery qry = OBDal.getInstance().getSession().createNativeQuery(sql);
     qry.setParameter("clientId", getClientId());
 
     @SuppressWarnings("unchecked")
--- a/src/org/openbravo/dal/service/DataPoolChecker.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/dal/service/DataPoolChecker.java	Tue Jul 24 10:44:21 2018 +0200
@@ -24,7 +24,7 @@
 import java.util.Map;
 
 import org.apache.commons.lang.StringUtils;
-import org.hibernate.Query;
+import org.hibernate.query.Query;
 import org.openbravo.base.provider.OBProvider;
 import org.openbravo.base.provider.OBSingleton;
 import org.openbravo.database.ExternalConnectionPool;
@@ -76,20 +76,19 @@
    * 
    * @return a new Map object with the mapping (Report_ID, POOL)
    */
-  @SuppressWarnings("unchecked")
   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 query = OBDal.getInstance().getSession().createQuery(hql.toString());
-    List<Object> queryResults = query.list();
+    Query<Object[]> query = OBDal.getInstance().getSession()
+        .createQuery(hql.toString(), Object[].class);
+    List<Object[]> queryResults = query.list();
+
     Map<String, String> selection = new HashMap<>(queryResults.size());
-    for (Object item : queryResults) {
-      final Object[] values = (Object[]) item;
+    for (Object[] values : queryResults) {
       selection.put(values[REPORT_ID].toString(), values[DATA_POOL].toString());
     }
-
     return selection;
   }
 
@@ -97,10 +96,10 @@
     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' ");
-    Query defaultPoolQuery = OBDal.getInstance().getSession().createQuery(hql.toString());
+    Query<String> defaultPoolQuery = OBDal.getInstance().getSession()
+        .createQuery(hql.toString(), String.class);
     defaultPoolQuery.setMaxResults(1);
-
-    setDefaultReadOnlyPool((String) defaultPoolQuery.uniqueResult());
+    setDefaultReadOnlyPool(defaultPoolQuery.uniqueResult());
   }
 
   /**
--- a/src/org/openbravo/dal/service/OBCriteria.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/dal/service/OBCriteria.java	Tue Jul 24 10:44:21 2018 +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-2017 Openbravo SLU 
+ * All portions are Copyright (C) 2008-2018 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -32,8 +32,8 @@
 import org.hibernate.criterion.Order;
 import org.hibernate.criterion.Projections;
 import org.hibernate.criterion.Restrictions;
-import org.hibernate.engine.SessionImplementor;
-import org.hibernate.impl.CriteriaImpl;
+import org.hibernate.engine.spi.SessionImplementor;
+import org.hibernate.internal.CriteriaImpl;
 import org.openbravo.base.model.Entity;
 import org.openbravo.base.structure.BaseOBObject;
 import org.openbravo.dal.core.OBContext;
@@ -184,14 +184,15 @@
 
     if (isFilterOnReadableOrganization() && e.isOrganizationPartOfKey()) {
       add(Restrictions.in("id." + PROPERTY_ORGANIZATION + ".id",
-          obContext.getReadableOrganizations()));
+          (Object[]) obContext.getReadableOrganizations()));
 
     } else if (isFilterOnReadableOrganization() && e.isOrganizationEnabled()) {
-      add(Restrictions.in(PROPERTY_ORGANIZATION + ".id", obContext.getReadableOrganizations()));
+      add(Restrictions.in(PROPERTY_ORGANIZATION + ".id",
+          (Object[]) obContext.getReadableOrganizations()));
     }
 
     if (isFilterOnReadableClients() && getEntity().isClientEnabled()) {
-      add(Restrictions.in(PROPERTY_CLIENT + ".id", obContext.getReadableClients()));
+      add(Restrictions.in(PROPERTY_CLIENT + ".id", (Object[]) obContext.getReadableClients()));
     }
 
     if (isFilterOnActive() && e.isActiveEnabled()) {
--- a/src/org/openbravo/dal/service/OBDal.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/dal/service/OBDal.java	Tue Jul 24 10:44:21 2018 +0200
@@ -31,11 +31,7 @@
 import org.hibernate.ObjectNotFoundException;
 import org.hibernate.Session;
 import org.hibernate.criterion.Restrictions;
-import org.hibernate.dialect.Dialect;
-import org.hibernate.dialect.function.SQLFunction;
-import org.hibernate.engine.SessionImplementor;
-import org.hibernate.impl.SessionFactoryImpl;
-import org.hibernate.jdbc.BorrowedConnectionProxy;
+import org.hibernate.engine.spi.SessionImplementor;
 import org.hibernate.stat.SessionStatistics;
 import org.openbravo.base.model.Entity;
 import org.openbravo.base.model.ModelProvider;
@@ -43,14 +39,11 @@
 import org.openbravo.base.model.UniqueConstraint;
 import org.openbravo.base.provider.OBNotSingleton;
 import org.openbravo.base.provider.OBProvider;
-import org.openbravo.base.session.SessionFactoryController;
 import org.openbravo.base.structure.BaseOBObject;
 import org.openbravo.base.structure.ClientEnabled;
 import org.openbravo.base.structure.OrganizationEnabled;
-import org.openbravo.dal.core.DalSessionFactory;
 import org.openbravo.dal.core.DalUtil;
 import org.openbravo.dal.core.OBContext;
-import org.openbravo.dal.core.SQLFunctionRegister;
 import org.openbravo.dal.core.SessionHandler;
 import org.openbravo.dal.security.SecurityChecker;
 import org.openbravo.database.ExternalConnectionPool;
@@ -150,24 +143,6 @@
   }
 
   /**
-   * Register a sql function in the session factory, after this call it can be used by queries.
-   * 
-   * @deprecated Use a {@link SQLFunctionRegister} instead. This method is slated for removal in the
-   *             upcoming releases.
-   */
-  @Deprecated
-  public void registerSQLFunction(String name, SQLFunction function) {
-    log.info("Using deprecated way of registering SQL functions in Hibernate", new Exception(
-        "Current Stack Trace"));
-    final DalSessionFactory dalSessionFactory = (DalSessionFactory) SessionFactoryController
-        .getInstance().getSessionFactory();
-
-    final Dialect dialect = ((SessionFactoryImpl) dalSessionFactory.getDelegateSessionFactory())
-        .getDialect();
-    dialect.getFunctions().put(name, function);
-  }
-
-  /**
    * After calling this method the active filter is disabled. Note that then the settings in
    * {@link OBQuery#setFilterOnActive(boolean)} and {@link OBCriteria#setFilterOnActive(boolean)}
    * will apply.
@@ -215,17 +190,9 @@
       flush();
     }
 
-    // NOTE: workaround for this issue:
-    // http://opensource.atlassian.com/projects/hibernate/browse/HHH-3529
-    final ClassLoader currentLoader = Thread.currentThread().getContextClassLoader();
-    try {
-      Thread.currentThread().setContextClassLoader(BorrowedConnectionProxy.class.getClassLoader());
-      final Connection connection = ((SessionImplementor) SessionHandler.getInstance().getSession(
-          poolName)).connection();
-      return connection;
-    } finally {
-      Thread.currentThread().setContextClassLoader(currentLoader);
-    }
+    final Connection connection = ((SessionImplementor) SessionHandler.getInstance().getSession(
+        poolName)).connection();
+    return connection;
   }
 
   /**
@@ -758,5 +725,4 @@
     final Entity e = ModelProvider.getInstance().getEntity(entityName);
     OBContext.getOBContext().getEntityAccessChecker().checkReadable(e);
   }
-
 }
\ No newline at end of file
--- a/src/org/openbravo/dal/service/OBQuery.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/dal/service/OBQuery.java	Tue Jul 24 10:44:21 2018 +0200
@@ -19,19 +19,22 @@
 
 package org.openbravo.dal.service;
 
-import java.util.ArrayList;
 import java.util.Collection;
 import java.util.HashMap;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
+import java.util.Map.Entry;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Stream;
 
 import org.apache.log4j.Logger;
 import org.hibernate.HibernateException;
-import org.hibernate.Query;
 import org.hibernate.ScrollMode;
 import org.hibernate.ScrollableResults;
 import org.hibernate.Session;
+import org.hibernate.query.Query;
 import org.openbravo.base.exception.OBException;
 import org.openbravo.base.model.Entity;
 import org.openbravo.base.structure.BaseOBObject;
@@ -66,7 +69,6 @@
   private String usedAlias = "";
   private String whereAndOrderBy;
   private Entity entity;
-  private List<Object> parameters;
   private Map<String, Object> namedParameters;
   private boolean filterOnReadableOrganizations = true;
   private boolean filterOnReadableClients = true;
@@ -93,7 +95,6 @@
    *           if the query returns more than one result
    * @see OBQuery#uniqueResultObject() uniqueResultObject for a version returning an Object
    */
-  @SuppressWarnings("unchecked")
   public E uniqueResult() {
     return (E) createQuery().uniqueResult();
   }
@@ -108,7 +109,7 @@
    * @see OBQuery#uniqueResult() uniqueResult for a type-safe version
    */
   public Object uniqueResultObject() {
-    return createQuery().uniqueResult();
+    return createQuery(Object.class).uniqueResult();
   }
 
   /**
@@ -117,19 +118,30 @@
    * 
    * @return list of objects retrieved from the database
    */
-  @SuppressWarnings("unchecked")
   public List<E> list() {
     return createQuery().list();
   }
 
   /**
+   * Makes it possible to get a {@link Stream} over the underlying Query object. Note that the
+   * {@link java.util.stream.Stream#close()} method should be invoked after processing the stream so
+   * that the underlying resources are deallocated right away.
+   * 
+   * @return a {@link Stream} over the underlying Query object.
+   */
+  public Stream<E> stream() {
+    return createQuery().stream();
+  }
+
+  /**
    * Queries the database using the where clauses and addition active, client and organization
    * filters. The order in the list is determined by order by clause. Returns an iterator over the
    * data.
    * 
    * @return iterator which walks over the list of objects in the db
+   * @deprecated
    */
-  @SuppressWarnings("unchecked")
+  @Deprecated
   public Iterator<E> iterate() {
     return createQuery().iterate();
   }
@@ -158,9 +170,10 @@
       final int index = qryStr.indexOf(FROM_SPACED) + FROM_SPACED.length();
       qryStr = qryStr.substring(index);
     }
-    final Query qry = getSession().createQuery("select count(*) " + FROM_SPACED + qryStr);
+    final Query<Number> qry = getSession().createQuery("select count(*) " + FROM_SPACED + qryStr,
+        Number.class);
     setParameters(qry);
-    return ((Number) qry.uniqueResult()).intValue();
+    return qry.uniqueResult().intValue();
   }
 
   /**
@@ -178,20 +191,17 @@
       final int index = qryStr.indexOf(FROM_SPACED) + FROM_SPACED.length();
       qryStr = qryStr.substring(index);
     }
-    final Query qry = getSession()
-        .createQuery("select " + usedAlias + "id " + FROM_SPACED + qryStr);
+    final Query<String> qry = getSession().createQuery(
+        "select " + usedAlias + "id " + FROM_SPACED + qryStr, String.class);
     setParameters(qry);
 
-    final ScrollableResults results = qry.scroll(ScrollMode.FORWARD_ONLY);
-    try {
+    try (ScrollableResults results = qry.scroll(ScrollMode.FORWARD_ONLY)) {
       while (results.next()) {
         final String id = results.getString(0);
         if (id.equals(targetId)) {
           return results.getRowNumber();
         }
       }
-    } finally {
-      results.close();
     }
     return -1;
   }
@@ -208,8 +218,10 @@
    * OBQuery instance. To generate the criteria of the deletion, it makes use of the whereclause and
    * extra filters (for readable organizations etc.).
    * 
-   * @return a new Hibernate Query object
+   * @return a new Hibernate Query object. Note that it does not have an specific type because
+   *         delete queries can not be typed.
    */
+  @SuppressWarnings("rawtypes")
   public Query deleteQuery() {
     final String qryStr = createQueryString();
     String whereClause;
@@ -221,14 +233,16 @@
       throw new OBException("Exception when creating delete query " + qryStr);
     }
 
+    StringBuilder deleteClause = new StringBuilder();
     try {
-      final Query qry = getSession().createQuery(
-          "DELETE FROM " + getEntity().getName() + " " + whereClause);
+      deleteClause.append("DELETE FROM ");
+      deleteClause.append(getEntity().getName() + " ");
+      deleteClause.append(whereClause);
+      final Query qry = getSession().createQuery(deleteClause.toString());
       setParameters(qry);
       return qry;
     } catch (final Exception e) {
-      throw new OBException("Exception when creating delete query " + "DELETE FROM "
-          + getEntity().getName() + " " + whereClause, e);
+      throw new OBException("Exception when creating delete query " + deleteClause.toString(), e);
     }
   }
 
@@ -238,10 +252,25 @@
    * 
    * @return a new Hibernate Query object
    */
-  public Query createQuery() {
+  @SuppressWarnings("unchecked")
+  public Query<E> createQuery() {
+    return (Query<E>) createQuery(BaseOBObject.class);
+  }
+
+  /**
+   * Creates a Hibernate Query object using the whereclause and extra filters (for readable
+   * organizations etc.). The Query will return objects with the type specified as parameter (unless
+   * a specific select clause is provided using the {@link #setSelectClause(String)} method).
+   *
+   * @param clz
+   *          the class of the query's resulting objects
+   * 
+   * @return a new Hibernate Query object
+   */
+  public <T extends Object> Query<T> createQuery(Class<T> clz) {
     final String qryStr = createQueryString();
     try {
-      final Query qry = getSession().createQuery(qryStr);
+      final Query<T> qry = getSession().createQuery(qryStr, clz);
       setParameters(qry);
       if (fetchSize > -1) {
         qry.setFetchSize(fetchSize);
@@ -441,36 +470,15 @@
     this.entity = entity;
   }
 
-  private void setParameters(Query qry) {
-    setPositionalParameters(qry);
-    setNamedParameters(qry);
-  }
-
-  private void setPositionalParameters(Query qry) {
-    final List<Object> localParameters = getParameters();
-    if (localParameters == null) {
-      return;
-    }
-    int pos = 0;
-    for (final Object param : localParameters) {
-      if (param instanceof BaseOBObject) {
-        qry.setEntity(pos++, param);
-      } else {
-        qry.setParameter(pos++, param);
-      }
-    }
-  }
-
-  private void setNamedParameters(Query qry) {
+  private void setParameters(Query<?> qry) {
     final Map<String, Object> localNamedParameters = getNamedParameters();
     if (localNamedParameters == null) {
       return;
     }
-    for (final String name : localNamedParameters.keySet()) {
-      final Object value = localNamedParameters.get(name);
-      if (value instanceof BaseOBObject) {
-        qry.setEntity(name, value);
-      } else if (value instanceof Collection<?>) {
+    for (Entry<String, Object> entry : localNamedParameters.entrySet()) {
+      final String name = entry.getKey();
+      final Object value = entry.getValue();
+      if (value instanceof Collection<?>) {
         qry.setParameterList(name, (Collection<?>) value);
       } else if (value instanceof String[]) {
         qry.setParameterList(name, (String[]) value);
@@ -478,7 +486,6 @@
         qry.setParameter(name, value);
       }
     }
-
   }
 
   /**
@@ -550,14 +557,11 @@
   }
 
   /**
-   * @return the parameters used in the query, this is the list of non-named parameters in the query
-   */
-  private List<Object> getParameters() {
-    return parameters;
-  }
-
-  /**
-   * Set the parameters in this query. These are the non-named parameters ('?').
+   * Set the non-named parameters ('?') in the query by converting them to named parameters. This
+   * conversion is done because legacy-style query parameters are no longer supported in Hibernate.
+   * 
+   * Note that this method also parses the where and order by clauses of the query to make use of
+   * the newly generated named parameters.
    * 
    * @param parameters
    *          the parameters which are set in the query without a name (e.g. as :?)
@@ -566,11 +570,27 @@
    */
   @Deprecated
   public void setParameters(List<Object> parameters) {
-    if (parameters == null) {
-      this.parameters = new ArrayList<>();
-    } else {
-      this.parameters = parameters;
+    converToNamedParameterQuery(parameters);
+  }
+
+  private void converToNamedParameterQuery(List<Object> parameters) {
+    if (parameters == null || parameters.isEmpty()) {
+      return;
     }
+    Pattern pattern = Pattern.compile("\\?");
+    Matcher matcher = pattern.matcher(whereAndOrderBy);
+    StringBuffer parsedHql = new StringBuffer();
+    int parameterCount = 0;
+    while (matcher.find()) {
+      String parameterName = "__p" + parameterCount;
+      matcher.appendReplacement(parsedHql, ":" + parameterName + " ");
+      setNamedParameter(parameterName, parameters.get(parameterCount));
+      parameterCount++;
+    }
+    matcher.appendTail(parsedHql);
+    Check.isTrue(parameterCount == parameters.size(),
+        "Could not convert legacy-style query parameters in: " + whereAndOrderBy);
+    whereAndOrderBy = parsedHql.toString();
   }
 
   /**
@@ -697,7 +717,9 @@
   }
 
   /**
-   * Defines a select clause for the underlying query.
+   * Defines a select clause for the underlying query. <b>Important Note</b>: this method can change
+   * the type of the object returned by the query, which is previously defined when instantiating
+   * the OBQuery object.
    * 
    * @param selectClause
    *          the select clause to be used by the underlying query.
--- a/src/org/openbravo/dal/xml/EntityResolver.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/dal/xml/EntityResolver.java	Tue Jul 24 10:44:21 2018 +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-2017 Openbravo SLU 
+ * All portions are Copyright (C) 2008-2018 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -412,7 +412,6 @@
 
   protected BaseOBObject doSearch(String id, Entity entity, String clientId, boolean filterOrgs,
       String orgId) {
-    final String[] searchOrgIds = getOrgIds(orgId);
     final OBCriteria<?> obc = OBDal.getInstance().createCriteria(entity.getName());
     obc.setFilterOnActive(false);
     obc.setFilterOnReadableClients(false);
@@ -424,7 +423,8 @@
       // Note the query is for other types than client but the client
       // property names
       // are good standard ones to use
-      obc.add(Restrictions.in(PROPERTY_ORGANIZATION + "." + Client.PROPERTY_ID, searchOrgIds));
+      obc.add(Restrictions.in(PROPERTY_ORGANIZATION + "." + Client.PROPERTY_ID,
+          (Object[]) getOrgIds(orgId)));
     }
     // same for here
     obc.add(Restrictions.eq(Organization.PROPERTY_ID, id));
@@ -527,16 +527,13 @@
         rdlCriteria.add(Restrictions.eq(ReferenceDataStore.PROPERTY_CLIENT + "."
             + Client.PROPERTY_ID, client.getId()));
       } else {
-        String[] clients = new String[2];
-        clients[0] = client.getId();
-        clients[1] = "0";
+        Object[] clients = { client.getId(), "0" };
         rdlCriteria.add(Restrictions.in(ReferenceDataStore.PROPERTY_CLIENT + "."
             + Client.PROPERTY_ID, clients));
       }
       if (orgId != null) {
-        final String[] searchOrgIds = getOrgIds(orgId);
         rdlCriteria.add(Restrictions.in(ReferenceDataStore.PROPERTY_ORGANIZATION + "."
-            + Organization.PROPERTY_ID, searchOrgIds));
+            + Organization.PROPERTY_ID, (Object[]) getOrgIds(orgId)));
       }
       rdlCriteria.add(Restrictions.eq(ReferenceDataStore.PROPERTY_TABLE + "." + Table.PROPERTY_ID,
           entity.getTableId()));
--- a/src/org/openbravo/erpCommon/ad_actionButton/MRPManufacturingPlanProcess.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/erpCommon/ad_actionButton/MRPManufacturingPlanProcess.java	Tue Jul 24 10:44:21 2018 +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) 2012-2013 Openbravo SLU
+ * All portions are Copyright (C) 2012-2018 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  *************************************************************************
@@ -23,9 +23,9 @@
 import java.util.List;
 
 import org.apache.log4j.Logger;
-import org.hibernate.Query;
 import org.hibernate.ScrollMode;
 import org.hibernate.ScrollableResults;
+import org.hibernate.query.Query;
 import org.openbravo.dal.core.OBContext;
 import org.openbravo.dal.service.OBDal;
 import org.openbravo.dal.service.OBQuery;
@@ -165,8 +165,9 @@
     deleteLines.append(" delete from " + ProductionRunLine.ENTITY_NAME);
     deleteLines.append(" where " + ProductionRunLine.PROPERTY_MANUFACTURINGPLAN + ".id = :prodRun");
     deleteLines.append("   and " + ProductionRunLine.PROPERTY_FIXED + " = false");
+    @SuppressWarnings("rawtypes")
     Query delete = OBDal.getInstance().getSession().createQuery(deleteLines.toString());
-    delete.setString("prodRun", strManufacturingMRPID);
+    delete.setParameter("prodRun", strManufacturingMRPID);
     delete.executeUpdate();
     OBDal.getInstance().flush();
   }
--- a/src/org/openbravo/erpCommon/ad_actionButton/ProcessGoods.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/erpCommon/ad_actionButton/ProcessGoods.java	Tue Jul 24 10:44:21 2018 +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) 2012-2017 Openbravo SLU
+ * All portions are Copyright (C) 2012-2018 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  *************************************************************************
@@ -33,7 +33,7 @@
 import javax.servlet.http.HttpServletResponse;
 
 import org.apache.commons.lang.StringUtils;
-import org.hibernate.Query;
+import org.hibernate.query.Query;
 import org.openbravo.base.filter.IsIDFilter;
 import org.openbravo.base.provider.OBProvider;
 import org.openbravo.base.secureApp.HttpSecureAppServlet;
@@ -370,7 +370,6 @@
     return data;
   }
 
-  @SuppressWarnings("unchecked")
   private List<String> getReceiptLinesWithoutStock(String receiptId) {
     StringBuffer where = new StringBuffer();
     where.append(" select iol." + ShipmentInOutLine.PROPERTY_ID);
@@ -392,7 +391,8 @@
         + ShipmentInOutLine.PROPERTY_ORDERUOM + ", '0')");
     where.append(" )");
 
-    Query qry = OBDal.getInstance().getSession().createQuery(where.toString());
+    Query<String> qry = OBDal.getInstance().getSession()
+        .createQuery(where.toString(), String.class);
     qry.setParameter("receipt", OBDal.getInstance().get(ShipmentInOut.class, receiptId));
     return qry.list();
   }
--- a/src/org/openbravo/erpCommon/ad_actionButton/SequenceProductCreate.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/erpCommon/ad_actionButton/SequenceProductCreate.java	Tue Jul 24 10:44:21 2018 +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 Openbravo SLU 
+ * All portions are Copyright (C) 2011-2018 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -21,7 +21,7 @@
 import java.math.BigDecimal;
 
 import org.apache.log4j.Logger;
-import org.hibernate.Query;
+import org.hibernate.query.Query;
 import org.openbravo.base.provider.OBProvider;
 import org.openbravo.dal.core.DalUtil;
 import org.openbravo.dal.core.OBContext;
@@ -191,9 +191,9 @@
   private static Long getLineNum(String SequenceId) throws Exception {
     String hql = "  SELECT COALESCE(MAX(l.lineNo),0)+10 AS DefaultValue FROM ManufacturingOperationProduct l WHERE l.mASequence.id= '"
         + SequenceId + "'";
-    Query q = OBDal.getInstance().getSession().createQuery(hql);
+    Query<Long> q = OBDal.getInstance().getSession().createQuery(hql, Long.class);
     try {
-      Long result = (Long) q.uniqueResult();
+      Long result = q.uniqueResult();
       return result == null ? 0L : result;
     } catch (Exception e) {
       // Unique result throws exception if more than one line is returned.
--- a/src/org/openbravo/erpCommon/ad_callouts/SL_BPartnerLocation.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/erpCommon/ad_callouts/SL_BPartnerLocation.java	Tue Jul 24 10:44:21 2018 +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-2016 Openbravo SLU
+ * All portions are Copyright (C) 2015-2018 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -23,7 +23,7 @@
 
 import org.apache.commons.lang.StringUtils;
 import org.apache.log4j.Logger;
-import org.hibernate.Query;
+import org.hibernate.query.Query;
 import org.openbravo.base.filter.IsIDFilter;
 import org.openbravo.base.filter.RequestFilter;
 import org.openbravo.base.filter.ValueListFilter;
@@ -70,10 +70,11 @@
             "where bpl.businessPartner.id = :bPartnerId " + //
             "and bpl.taxLocation = true " + //
             "and c.id <> :countryId "; //
-        Query query = OBDal.getInstance().getSession().createQuery(hql.toString());
-        query.setString("bPartnerId", bPartnerId);
-        query.setString("countryId", location.getCountry().getId());
-        int otherCountriesTaxLocationYes = ((Long) query.list().get(0)).intValue();
+        Query<Long> query = OBDal.getInstance().getSession()
+            .createQuery(hql.toString(), Long.class);
+        query.setParameter("bPartnerId", bPartnerId);
+        query.setParameter("countryId", location.getCountry().getId());
+        int otherCountriesTaxLocationYes = query.list().get(0).intValue();
 
         if (otherCountriesTaxLocationYes > 1) {
           // Detected several countries defined as Tax Location
@@ -91,10 +92,10 @@
               "inner join ad.country as c " + //
               "where bpl.businessPartner.id = :bPartnerId " + //
               "and c.id <> :countryId "; //
-          query = OBDal.getInstance().getSession().createQuery(hql.toString());
-          query.setString("bPartnerId", bPartnerId);
-          query.setString("countryId", location.getCountry().getId());
-          int otherCountries = ((Long) query.list().get(0)).intValue();
+          query = OBDal.getInstance().getSession().createQuery(hql.toString(), Long.class);
+          query.setParameter("bPartnerId", bPartnerId);
+          query.setParameter("countryId", location.getCountry().getId());
+          int otherCountries = query.list().get(0).intValue();
 
           if (otherCountries > 0) {
             hql = "" + //
@@ -105,10 +106,10 @@
                 "where bpl.businessPartner.id = :bPartnerId " + //
                 "and c.id = :countryId " + //
                 "and bpl.taxLocation = true ";
-            query = OBDal.getInstance().getSession().createQuery(hql.toString());
-            query.setString("bPartnerId", bPartnerId);
-            query.setString("countryId", location.getCountry().getId());
-            int thisCountryTaxLocationYes = ((Long) query.list().get(0)).intValue();
+            query = OBDal.getInstance().getSession().createQuery(hql.toString(), Long.class);
+            query.setParameter("bPartnerId", bPartnerId);
+            query.setParameter("countryId", location.getCountry().getId());
+            int thisCountryTaxLocationYes = query.list().get(0).intValue();
 
             if (thisCountryTaxLocationYes == 0) {
               // Detected several countries, neither of them defined as Tax Location
--- a/src/org/openbravo/erpCommon/ad_callouts/SL_LandedCost_InvoiceLine.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/erpCommon/ad_callouts/SL_LandedCost_InvoiceLine.java	Tue Jul 24 10:44:21 2018 +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) 2014-2016 Openbravo SLU 
+ * All portions are Copyright (C) 2014-2018 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -22,8 +22,8 @@
 
 import javax.servlet.ServletException;
 
-import org.hibernate.Query;
 import org.hibernate.Session;
+import org.hibernate.query.Query;
 import org.openbravo.base.secureApp.VariablesSecureApp;
 import org.openbravo.dal.core.OBContext;
 import org.openbravo.dal.service.OBDal;
@@ -57,7 +57,7 @@
       hqlString.append(" from LandedCostCost as e");
       hqlString.append(" where e.invoiceLine = :invoiceLine");
       final Session session = OBDal.getInstance().getSession();
-      final Query query = session.createQuery(hqlString.toString());
+      final Query<BigDecimal> query = session.createQuery(hqlString.toString(), BigDecimal.class);
       query.setParameter("invoiceLine", invoiceLine);
       totalAssigned = (BigDecimal) query.uniqueResult();
 
--- a/src/org/openbravo/erpCommon/ad_callouts/SL_ProductPrice_PriceListVersion.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/erpCommon/ad_callouts/SL_ProductPrice_PriceListVersion.java	Tue Jul 24 10:44:21 2018 +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) 2012-2017 Openbravo SLU 
+ * All portions are Copyright (C) 2012-2018 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -21,7 +21,7 @@
 import javax.servlet.ServletException;
 
 import org.apache.commons.lang.StringUtils;
-import org.hibernate.Query;
+import org.hibernate.query.Query;
 import org.openbravo.base.filter.IsIDFilter;
 import org.openbravo.dal.core.OBContext;
 import org.openbravo.dal.service.OBDal;
@@ -67,7 +67,8 @@
       hqlString.append(" from " + RoleOrganization.ENTITY_NAME);
       hqlString.append(" where " + RoleOrganization.PROPERTY_ROLE + ".id = :roleId");
       hqlString.append(" and " + RoleOrganization.PROPERTY_ORGANIZATION + ".id = :orgId");
-      Query query = OBDal.getInstance().getSession().createQuery(hqlString.toString());
+      Query<String> query = OBDal.getInstance().getSession()
+          .createQuery(hqlString.toString(), String.class);
       query.setParameter("roleId", roleId);
       query.setParameter("orgId", orgId);
       query.setMaxResults(1);
--- a/src/org/openbravo/erpCommon/ad_forms/DocLineCashVATReady_PaymentTransactionReconciliation.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/erpCommon/ad_forms/DocLineCashVATReady_PaymentTransactionReconciliation.java	Tue Jul 24 10:44:21 2018 +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-2016 Openbravo SLU
+ * All portions are Copyright (C) 2013-2018 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -25,7 +25,7 @@
 import java.util.Set;
 
 import org.apache.commons.lang.StringUtils;
-import org.hibernate.Query;
+import org.hibernate.query.Query;
 import org.openbravo.dal.core.OBContext;
 import org.openbravo.dal.service.OBDal;
 import org.openbravo.model.common.invoice.InvoiceTaxCashVAT_V;
@@ -106,7 +106,7 @@
             + ".id = :finPaymentDetailID ");
         hql.append(" and itcv." + InvoiceTaxCashVAT_V.PROPERTY_CANCELED + " = false");
         hql.append(" and itcv." + InvoiceTaxCashVAT_V.PROPERTY_ACTIVE + " = true");
-        Query obq = OBDal.getInstance().getSession().createQuery(hql.toString());
+        Query<String> obq = OBDal.getInstance().getSession().createQuery(hql.toString());
         obq.setParameter("finPaymentDetailID", finPaymentDetailID);
         this.invoiceTaxCashVAT_V.addAll(obq.list());
       } finally {
--- a/src/org/openbravo/erpCommon/ad_forms/SQLExecutor_Query.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/erpCommon/ad_forms/SQLExecutor_Query.java	Tue Jul 24 10:44:21 2018 +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) 2001-2017 Openbravo SLU 
+ * All portions are Copyright (C) 2001-2018 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -28,7 +28,7 @@
 
 import org.apache.commons.lang.StringUtils;
 import org.apache.log4j.Logger;
-import org.hibernate.SQLQuery;
+import org.hibernate.query.NativeQuery;
 import org.openbravo.dal.service.OBDal;
 import org.openbravo.data.FieldProvider;
 import org.openbravo.database.ConnectionProvider;
@@ -63,7 +63,8 @@
     PreparedStatement st = null;
     Vector<SQLExecutor_Query> vector = new Vector<>(0);
     try {
-      SQLQuery sqlQuery = OBDal.getInstance().getSession().createSQLQuery(strSQL);
+      @SuppressWarnings("rawtypes")
+      NativeQuery sqlQuery = OBDal.getInstance().getSession().createNativeQuery(strSQL);
       sqlQuery.setFirstResult(firstRegister);
       sqlQuery.setMaxResults(numberRegisters);
 
--- a/src/org/openbravo/erpCommon/ad_process/HeartbeatProcess.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/erpCommon/ad_process/HeartbeatProcess.java	Tue Jul 24 10:44:21 2018 +0200
@@ -30,7 +30,6 @@
 import java.text.ParseException;
 import java.text.SimpleDateFormat;
 import java.util.ArrayList;
-import java.util.Arrays;
 import java.util.Date;
 import java.util.Enumeration;
 import java.util.List;
@@ -38,15 +37,17 @@
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 
+import javax.persistence.Tuple;
+import javax.persistence.TupleElement;
 import javax.servlet.ServletException;
 
 import org.apache.log4j.Logger;
 import org.codehaus.jettison.json.JSONArray;
 import org.codehaus.jettison.json.JSONException;
 import org.codehaus.jettison.json.JSONObject;
-import org.hibernate.Query;
 import org.hibernate.Session;
 import org.hibernate.criterion.Restrictions;
+import org.hibernate.query.Query;
 import org.openbravo.base.provider.OBProvider;
 import org.openbravo.base.secureApp.VariablesSecureApp;
 import org.openbravo.dal.core.OBContext;
@@ -558,12 +559,11 @@
    *          The identifier of the beat on the heartbeat server.
    * @throws JSONException
    */
-  @SuppressWarnings("unchecked")
   private void processCustomQueries(JSONArray jsonArrayCQueries, String beatId)
       throws JSONException {
-    if ("null".equals(jsonArrayCQueries.get(0)))
+    if ("null".equals(jsonArrayCQueries.get(0))) {
       return;
-
+    }
     JSONObject jsonObjectCQReturn = new JSONObject();
     for (int i = 0; i < jsonArrayCQueries.length(); i++) {
       JSONObject jsonCustomQuery = (JSONObject) jsonArrayCQueries.get(i);
@@ -577,41 +577,36 @@
           HeartbeatLogCustomQuery hbLogCQ = logCustomQuery(strQName, strQType, strHQL);
 
           Session obSession = OBDal.getInstance().getSession();
-          Query customQuery = obSession.createQuery(strHQL);
-          String[] properties = customQuery.getReturnAliases();
+          Query<Tuple> customQuery = obSession.createQuery(strHQL, Tuple.class);
           JSONArray jsonArrayResultRows = new JSONArray();
           int row = 0;
-
-          for (Object objResult : (List<Object>) customQuery.list()) {
+          List<Tuple> tupleList = customQuery.list();
+          List<String> properties = null;
+          boolean initProperties = true;
+          for (Tuple tuple : tupleList) {
             row += 1;
             JSONArray jsonArrayResultRowValues = new JSONArray();
-
-            Object[] resultList = new Object[1];
-            if (objResult instanceof Object[])
-              resultList = (Object[]) objResult;
-            else
-              resultList[0] = objResult;
-
-            for (int j = 0; j < resultList.length; j++) {
-              jsonArrayResultRowValues.put(resultList[j]);
-
-              String fieldName = null;
-              if (properties != null && properties.length > j) {
-                fieldName = properties[j];
+            properties = new ArrayList<>();
+            int j = 0;
+            for (TupleElement<?> tupleElement : tuple.getElements()) {
+              jsonArrayResultRowValues.put(tuple.get(j));
+              String alias = tupleElement.getAlias();
+              if (initProperties) {
+                properties.add(alias);
               }
-              if (fieldName == null) {
-                fieldName = "??";
-              }
-              logCustomQueryResult(hbLogCQ, row, fieldName, resultList[j].toString());
+              String fieldName = alias != null ? alias : "??";
+              logCustomQueryResult(hbLogCQ, row, fieldName, tuple.get(j).toString());
             }
             jsonArrayResultRows.put(jsonArrayResultRowValues);
+            initProperties = false;
           }
 
-          if (customQuery.list().isEmpty())
+          if (tupleList.isEmpty()) {
             jsonArrayResultRows.put("null");
+          }
 
           JSONObject jsonResult = new JSONObject();
-          jsonResult.put("properties", properties == null ? null : Arrays.asList(properties));
+          jsonResult.put("properties", properties == null ? null : properties);
           jsonResult.put("values", jsonArrayResultRows);
           jsonObjectCQReturn.put(strQId, jsonResult);
         } else {
--- a/src/org/openbravo/erpCommon/ad_process/UpdateActuals.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/erpCommon/ad_process/UpdateActuals.java	Tue Jul 24 10:44:21 2018 +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) 2012-2017 Openbravo SLU
+ * All portions are Copyright (C) 2012-2018 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -24,7 +24,7 @@
 
 import org.apache.commons.lang.StringUtils;
 import org.apache.log4j.Logger;
-import org.hibernate.Query;
+import org.hibernate.query.Query;
 import org.openbravo.dal.core.OBContext;
 import org.openbravo.dal.service.OBDal;
 import org.openbravo.erpCommon.utility.OBError;
@@ -168,28 +168,28 @@
         if (!"".equals(user1)) {
           queryString.append(" and e.ndDimension.id in (").append(user2Tree).append(")");
         }
-        Query query = OBDal.getInstance().getSession().createQuery(queryString.toString());
+        Query<Object[]> query = OBDal.getInstance().getSession()
+            .createQuery(queryString.toString(), Object[].class);
         query.setReadOnly(true);
-        query.setString("accountingSchema", accountingSchema);
+        query.setParameter("accountingSchema", accountingSchema);
         if (!"".equals(businessPartner))
-          query.setString("businessPartner", businessPartner);
+          query.setParameter("businessPartner", businessPartner);
         if (StringUtils.isNotEmpty(businessPartnerCategory)) {
-          query.setString("businessPartnerCategory", businessPartnerCategory);
+          query.setParameter("businessPartnerCategory", businessPartnerCategory);
         }
         if (!"".equals(period))
-          query.setString("period", period);
+          query.setParameter("period", period);
         if (!"".equals(product))
-          query.setString("product", product);
+          query.setParameter("product", product);
 
         log4j.debug("Query String" + query.getQueryString());
 
         BigDecimal credit = BigDecimal.ZERO;
         BigDecimal debit = BigDecimal.ZERO;
-        for (Object obj : query.list()) {
-          if (obj != null) {
-            Object[] row = (Object[]) obj;
-            credit = (BigDecimal) ((row[0] != null) ? row[0] : new BigDecimal(0));
-            debit = (BigDecimal) ((row[1] != null) ? row[1] : new BigDecimal(0));
+        for (Object[] row : query.list()) {
+          if (row != null) {
+            credit = (row[0] != null) ? (BigDecimal) row[0] : new BigDecimal(0);
+            debit = (row[1] != null) ? (BigDecimal) row[1] : new BigDecimal(0);
           }
         }
 
--- a/src/org/openbravo/erpCommon/ad_process/assets/AssetLinearDepreciationMethodProcess.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/erpCommon/ad_process/assets/AssetLinearDepreciationMethodProcess.java	Tue Jul 24 10:44:21 2018 +0200
@@ -29,8 +29,8 @@
 import java.util.Map;
 
 import org.apache.log4j.Logger;
-import org.hibernate.Query;
 import org.hibernate.criterion.Restrictions;
+import org.hibernate.query.Query;
 import org.openbravo.advpaymentmngt.utility.FIN_Utility;
 import org.openbravo.base.exception.OBException;
 import org.openbravo.base.provider.OBProvider;
@@ -730,13 +730,12 @@
   private Long getMaxSeqNoAsset(Asset asset) {
     StringBuilder hql = new StringBuilder();
     hql.append(" select coalesce(max(al.sEQNoAsset), 0) as maxSeqNoAsset ");
-    hql.append(" from FinancialMgmtAmortizationLine as al where al.asset.id = :assetId ");
-    Query query = OBDal.getInstance().getSession().createQuery(hql.toString());
+    hql.append(" from FinancialMgmtAmortizationLine as al where al.asset.id = :assetId");
+    Query<Long> query = OBDal.getInstance().getSession().createQuery(hql.toString(), Long.class);
     query.setParameter("assetId", asset.getId());
-    for (Object obj : query.list()) {
-      if (obj != null) {
-        return (Long) obj;
-      }
+    Long maxSeqNoAsset = query.uniqueResult();
+    if (maxSeqNoAsset != null) {
+      return maxSeqNoAsset;
     }
     return 0l;
   }
@@ -752,13 +751,12 @@
   private Long getMaxLineNo(Amortization amortization) {
     StringBuilder hql = new StringBuilder();
     hql.append(" select coalesce(max(al.lineNo), 0) as maxSeqNoAsset ");
-    hql.append(" from FinancialMgmtAmortizationLine as al where al.amortization.id = :amortizationId ");
-    Query query = OBDal.getInstance().getSession().createQuery(hql.toString());
+    hql.append(" from FinancialMgmtAmortizationLine as al where al.amortization.id = :amortizationId");
+    Query<Long> query = OBDal.getInstance().getSession().createQuery(hql.toString(), Long.class);
     query.setParameter("amortizationId", amortization.getId());
-    for (Object obj : query.list()) {
-      if (obj != null) {
-        return (Long) obj;
-      }
+    Long maxSeqNoAsset = query.uniqueResult();
+    if (maxSeqNoAsset != null) {
+      return maxSeqNoAsset;
     }
     return 0l;
   }
--- a/src/org/openbravo/erpCommon/ad_reports/GeneralAccountingReports.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/erpCommon/ad_reports/GeneralAccountingReports.java	Tue Jul 24 10:44:21 2018 +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) 2001-2017 Openbravo SLU 
+ * All portions are Copyright (C) 2001-2018 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -37,9 +37,9 @@
 import org.codehaus.jettison.json.JSONArray;
 import org.codehaus.jettison.json.JSONException;
 import org.codehaus.jettison.json.JSONObject;
-import org.hibernate.Query;
 import org.hibernate.Session;
 import org.hibernate.criterion.Restrictions;
+import org.hibernate.query.Query;
 import org.openbravo.base.secureApp.HttpSecureAppServlet;
 import org.openbravo.base.secureApp.VariablesSecureApp;
 import org.openbravo.dal.core.OBContext;
@@ -515,11 +515,10 @@
     hqlString
         .append(" where p.year = y  and p.endingDate < :date and y.calendar = :calendar order by p.startingDate");
     final Session session = OBDal.getReadOnlyInstance().getSession();
-    final Query query = session.createQuery(hqlString.toString());
+    final Query<Year> query = session.createQuery(hqlString.toString(), Year.class);
     query.setParameter("date", startingDate);
     query.setParameter("calendar", calendar);
-    for (Object resultObject : query.list()) {
-      final Year previousYear = (Year) resultObject;
+    for (Year previousYear : query.list()) {
       if (!(result.contains(previousYear))) {
         result.add(previousYear);
       }
@@ -537,14 +536,11 @@
     hqlString.append(" where p.year = :year");
 
     final Session session = OBDal.getReadOnlyInstance().getSession();
-    final Query query = session.createQuery(hqlString.toString());
+    final Query<Object[]> query = session.createQuery(hqlString.toString(), Object[].class);
     query.setParameter("year", year);
-    for (Object resultObject : query.list()) {
-      if (resultObject.getClass().isArray()) {
-        final Object[] values = (Object[]) resultObject;
-        result.put("startingDate", (Date) values[0]);
-        result.put("endingDate", (Date) values[1]);
-      }
+    for (Object[] values : query.list()) {
+      result.put("startingDate", (Date) values[0]);
+      result.put("endingDate", (Date) values[1]);
     }
     return result;
   }
@@ -704,7 +700,6 @@
     out.close();
   }
 
-  @SuppressWarnings("unchecked")
   private List<String> getRoleOrganizationList(String roleId) {
     try {
       OBContext.setAdminMode(false);
@@ -712,7 +707,8 @@
       hqlString.append(" select " + RoleOrganization.PROPERTY_ORGANIZATION + ".id");
       hqlString.append(" from " + RoleOrganization.ENTITY_NAME);
       hqlString.append(" where " + RoleOrganization.PROPERTY_ROLE + ".id = :roleId");
-      Query query = OBDal.getReadOnlyInstance().getSession().createQuery(hqlString.toString());
+      Query<String> query = OBDal.getReadOnlyInstance().getSession()
+          .createQuery(hqlString.toString(), String.class);
       query.setParameter("roleId", roleId);
       return query.list();
     } finally {
--- a/src/org/openbravo/erpCommon/ad_reports/ReportGeneralLedgerJournal.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/erpCommon/ad_reports/ReportGeneralLedgerJournal.java	Tue Jul 24 10:44:21 2018 +0200
@@ -37,7 +37,7 @@
 import org.codehaus.jettison.json.JSONArray;
 import org.codehaus.jettison.json.JSONException;
 import org.codehaus.jettison.json.JSONObject;
-import org.hibernate.Query;
+import org.hibernate.query.Query;
 import org.openbravo.base.secureApp.HttpSecureAppServlet;
 import org.openbravo.base.secureApp.VariablesHistory;
 import org.openbravo.base.secureApp.VariablesSecureApp;
@@ -1145,11 +1145,12 @@
       where.append(" and d." + DocumentType.PROPERTY_CLIENT + ".id = :client");
       where.append(" group by d." + DocumentType.PROPERTY_DOCUMENTCATEGORY);
       where.append(" , t." + Table.PROPERTY_DBTABLENAME);
-      Query qry = OBDal.getReadOnlyInstance().getSession().createQuery(where.toString());
+      Query<String> qry = OBDal.getReadOnlyInstance().getSession()
+          .createQuery(where.toString(), String.class);
       qry.setMaxResults(1);
       qry.setParameter("document", strDocument);
       qry.setParameter("client", strClient);
-      String tablename = (String) qry.uniqueResult();
+      String tablename = qry.uniqueResult();
 
       if (StringUtils.isBlank(tablename)) {
         return null;
--- a/src/org/openbravo/erpCommon/ad_reports/ReportValuationStock.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/erpCommon/ad_reports/ReportValuationStock.java	Tue Jul 24 10:44:21 2018 +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) 2001-2017 Openbravo SLU 
+ * All portions are Copyright (C) 2001-2018 Openbravo SLU 
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -36,7 +36,7 @@
 import javax.servlet.http.HttpServletResponse;
 
 import org.apache.commons.lang.StringUtils;
-import org.hibernate.Query;
+import org.hibernate.query.Query;
 import org.openbravo.base.exception.OBException;
 import org.openbravo.base.filter.IsIDFilter;
 import org.openbravo.base.secureApp.HttpSecureAppServlet;
@@ -604,7 +604,6 @@
     }
   }
 
-  @SuppressWarnings("unchecked")
   private List<String> getWarehouses(String clientId, String orgId) {
     final OrganizationStructureProvider osp = OBContext.getOBContext()
         .getOrganizationStructureProvider(clientId);
@@ -613,10 +612,11 @@
     hqlString.append(" from Warehouse as e");
     hqlString.append(" where e.organization.id in (:orgList)");
     hqlString.append(" and e.client.id = :clientId");
-    Query qry = OBDal.getReadOnlyInstance().getSession().createQuery(hqlString.toString());
+    Query<String> qry = OBDal.getReadOnlyInstance().getSession()
+        .createQuery(hqlString.toString(), String.class);
     qry.setParameterList("orgList", osp.getNaturalTree(orgId));
     qry.setParameter("clientId", clientId);
-    return (List<String>) qry.list();
+    return qry.list();
   }
 
   public String getServletInfo() {
--- a/src/org/openbravo/erpCommon/businessUtility/CancelAndReplaceUtils.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/erpCommon/businessUtility/CancelAndReplaceUtils.java	Tue Jul 24 10:44:21 2018 +0200
@@ -32,11 +32,11 @@
 import org.codehaus.jettison.json.JSONException;
 import org.codehaus.jettison.json.JSONObject;
 import org.hibernate.LockOptions;
-import org.hibernate.Query;
 import org.hibernate.ScrollMode;
 import org.hibernate.ScrollableResults;
 import org.hibernate.Session;
 import org.hibernate.criterion.Restrictions;
+import org.hibernate.query.Query;
 import org.openbravo.advpaymentmngt.process.FIN_AddPayment;
 import org.openbravo.advpaymentmngt.process.FIN_PaymentProcess;
 import org.openbravo.advpaymentmngt.utility.FIN_Utility;
@@ -199,7 +199,8 @@
     hql.append(" where rol.orderlineServiceRelationList is not empty");
     hql.append(" and ol.salesOrder.id = :orderId");
 
-    Query query = OBDal.getInstance().getSession().createQuery(hql.toString());
+    Query<OrderLine> query = OBDal.getInstance().getSession()
+        .createQuery(hql.toString(), OrderLine.class);
     query.setParameter("orderId", order.getId());
     return query.scroll(ScrollMode.FORWARD_ONLY);
   }
@@ -358,7 +359,8 @@
       hql.append("FROM MaterialMgmtShipmentInOutLine AS sl ");
       hql.append("WHERE sl.salesOrderLine = ol) ");
       hql.append("AND ol.salesOrder.id = :orderId");
-      final Query query = OBDal.getInstance().getSession().createQuery(hql.toString());
+      final Query<Integer> query = OBDal.getInstance().getSession()
+          .createQuery(hql.toString(), Integer.class);
       query.setParameter("orderId", oldOrderId);
       query.setMaxResults(1);
       final boolean hasShipment = query.uniqueResult() != null;
@@ -1254,10 +1256,11 @@
             + FIN_PaymentScheduleDetail.PROPERTY_ORDERPAYMENTSCHEDULE
             + ".id =:paymentScheduleId and psd."
             + FIN_PaymentScheduleDetail.PROPERTY_PAYMENTDETAILS + " is null";
-        final Query qry = OBDal.getInstance().getSession().createQuery(countHql);
+        final Query<BigDecimal> qry = OBDal.getInstance().getSession()
+            .createQuery(countHql, BigDecimal.class);
         qry.setParameter("paymentScheduleId", paymentSchedule.getId());
         qry.setMaxResults(1);
-        BigDecimal outstandingAmount = (BigDecimal) qry.uniqueResult();
+        BigDecimal outstandingAmount = qry.uniqueResult();
         BigDecimal paidAmount = paymentSchedule.getAmount().subtract(outstandingAmount);
         BigDecimal negativeAmount = BigDecimal.ZERO;
 
@@ -1637,11 +1640,11 @@
     StringBuilder where = new StringBuilder("select c from " + Order.ENTITY_NAME
         + " c where id = :id");
     final Session session = OBDal.getInstance().getSession();
-    final Query query = session.createQuery(where.toString());
+    final Query<Order> query = session.createQuery(where.toString(), Order.class);
     query.setParameter("id", order.getId());
     query.setMaxResults(1);
     query.setLockOptions(LockOptions.UPGRADE);
-    return (Order) query.uniqueResult();
+    return query.uniqueResult();
   }
 
 }
--- a/src/org/openbravo/erpCommon/businessUtility/InitialSetupUtility.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/erpCommon/businessUtility/InitialSetupUtility.java	Tue Jul 24 10:44:21 2018 +0200
@@ -293,7 +293,8 @@
    *             trees defined in the DA_TreeType type list reference Returns the relation of trees
    *             defined in the reference list of the application dictionary called AD_TreeType Type
    * 
-   * @return java.util.List&lt;org.openbravo.model.ad.domain.List&gt;: the relation of AD list elements
+   * @return java.util.List&lt;org.openbravo.model.ad.domain.List&gt;: the relation of AD list
+   *         elements
    * @throws Exception
    */
   @Deprecated
@@ -960,9 +961,9 @@
    * @param treeNodes
    *          relation of nodes in ADTreeNode belonging to the accounting tree to sort out
    * @param mapSequence
-   *          HashMap&lt;String,Long&gt; where the String belongs to the value of a c_elementvalue, and
-   *          Long to the sequence that must be assigned to the node that represents that element
-   *          value in ADTreeNode
+   *          HashMap&lt;String,Long&gt; where the String belongs to the value of a c_elementvalue,
+   *          and Long to the sequence that must be assigned to the node that represents that
+   *          element value in ADTreeNode
    * @param mapElementValueValue
    *          each tree node in treeNodes has one entry in mapElementValueId to link it's value with
    *          the c_elementvalue_id of that element in c_elementvalue table
@@ -1876,7 +1877,8 @@
    * Returns the relation of ad_ref_list elements for the reference with AD_Reference_id='181'
    * (Acct.schema elements)
    * 
-   * @return List&lt;org.openbravo.model.ad.domain.List&gt; with the relation of ad_ref_list elements
+   * @return List&lt;org.openbravo.model.ad.domain.List&gt; with the relation of ad_ref_list
+   *         elements
    * @throws Exception
    */
   public static List<org.openbravo.model.ad.domain.List> getAcctSchemaElements() throws Exception {
@@ -1942,8 +1944,8 @@
       OBCriteria<DataSet> obc = OBDal.getInstance().createCriteria(DataSet.class);
       obc.createAlias(DataSet.PROPERTY_MODULE, "m");
       obc.add(Restrictions.eq(DataSet.PROPERTY_MODULE, module));
-      String[] organizationAccessLevel = { "3", "1" };
-      String[] systemAccessLevel = { "3", "6" };
+      Object[] organizationAccessLevel = { "3", "1" };
+      Object[] systemAccessLevel = { "3", "6" };
       obc.add(Restrictions.or(Restrictions.and(
           Restrictions.ne(DataSet.PROPERTY_ORGANIZATION, getZeroOrg()),
           Restrictions.in(DataSet.PROPERTY_DATAACCESSLEVEL, organizationAccessLevel)), Restrictions
--- a/src/org/openbravo/erpCommon/businessUtility/PriceAdjustment.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/erpCommon/businessUtility/PriceAdjustment.java	Tue Jul 24 10:44:21 2018 +0200
@@ -34,6 +34,7 @@
 import org.openbravo.dal.service.OBDal;
 import org.openbravo.dal.service.OBQuery;
 import org.openbravo.model.common.currency.Currency;
+import org.openbravo.model.common.enterprise.Organization;
 import org.openbravo.model.common.invoice.Invoice;
 import org.openbravo.model.common.order.Order;
 import org.openbravo.model.common.plm.Product;
@@ -146,7 +147,7 @@
     String hql = "as p ";
     hql += "where active = true ";
     hql += "and client = :client ";
-    hql += "and ad_isorgincluded(:org, p.organization.id, p.client.id) <> -1 ";
+    hql += "and ad_isorgincluded(:orgId, p.organization.id, p.client.id) <> -1 ";
     hql += "and (endingDate is null or trunc(endingDate) + 1 > :date) ";
     hql += "and trunc(startingDate)<=:date ";
     hql += "and p.discountType.id = '5D4BAF6BB86D4D2C9ED3D5A6FC051579' ";
@@ -240,13 +241,13 @@
     hql += "         from PricingAdjustmentOrganization o";
     hql += "        where active = true";
     hql += "          and o.priceAdjustment = p";
-    hql += "          and o.organization.id = :org)) ";
+    hql += "          and o.organization.id = :orgId)) ";
     hql += "   or (includedOrganizations='N' ";
     hql += "  and  exists (select 1 ";
     hql += "         from PricingAdjustmentOrganization o";
     hql += "        where active = true";
     hql += "          and o.priceAdjustment = p";
-    hql += "          and o.organization.id = :org )) ";
+    hql += "          and o.organization.id = :orgId )) ";
     hql += "    ) ";
 
     // product characteristic
@@ -286,7 +287,8 @@
     OBQuery<org.openbravo.model.pricing.priceadjustment.PriceAdjustment> q = OBDal.getInstance()
         .createQuery(org.openbravo.model.pricing.priceadjustment.PriceAdjustment.class, hql);
     q.setNamedParameter("client", orderOrInvoice.get(Invoice.PROPERTY_CLIENT));
-    q.setNamedParameter("org", orderOrInvoice.get(Invoice.PROPERTY_ORGANIZATION));
+    q.setNamedParameter("orgId",
+        ((Organization) orderOrInvoice.get(Invoice.PROPERTY_ORGANIZATION)).getId());
     q.setNamedParameter("priceList", orderOrInvoice.get(Invoice.PROPERTY_PRICELIST));
     q.setNamedParameter("bp", orderOrInvoice.get(Invoice.PROPERTY_BUSINESSPARTNER));
 
--- a/src/org/openbravo/erpCommon/obps/ActivationKey.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/erpCommon/obps/ActivationKey.java	Tue Jul 24 10:44:21 2018 +0200
@@ -62,9 +62,9 @@
 import org.apache.log4j.Logger;
 import org.codehaus.jettison.json.JSONException;
 import org.codehaus.jettison.json.JSONObject;
-import org.hibernate.Query;
 import org.hibernate.criterion.Order;
 import org.hibernate.criterion.Restrictions;
+import org.hibernate.query.Query;
 import org.openbravo.base.exception.OBException;
 import org.openbravo.base.secureApp.VariablesSecureApp;
 import org.openbravo.base.session.OBPropertiesProvider;
@@ -1701,7 +1701,8 @@
     hql.append("having count(*) > :maxWsPerDay\n");
     hql.append(" order by 1\n");
 
-    Query qExceededDays = OBDal.getInstance().getSession().createQuery(hql.toString());
+    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);
--- a/src/org/openbravo/erpCommon/obps/ActiveInstanceProcess.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/erpCommon/obps/ActiveInstanceProcess.java	Tue Jul 24 10:44:21 2018 +0200
@@ -26,7 +26,7 @@
 
 import org.apache.commons.lang.StringUtils;
 import org.apache.log4j.Logger;
-import org.hibernate.Query;
+import org.hibernate.query.Query;
 import org.openbravo.base.provider.OBProvider;
 import org.openbravo.base.session.SessionFactoryController;
 import org.openbravo.base.weld.WeldUtils;
@@ -182,6 +182,7 @@
     }
   }
 
+  @SuppressWarnings("rawtypes")
   public static void updateShowProductionFields(String value) {
     String hql = "update ADPreference set searchKey = :value where property = 'showMRPandProductionFields' and module.id is null";
     Query q = OBDal.getInstance().getSession().createQuery(hql);
--- a/src/org/openbravo/erpCommon/security/Login.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/erpCommon/security/Login.java	Tue Jul 24 10:44:21 2018 +0200
@@ -29,7 +29,7 @@
 import javax.servlet.http.HttpServletResponse;
 
 import org.apache.commons.lang.StringUtils;
-import org.hibernate.Query;
+import org.hibernate.query.Query;
 import org.openbravo.base.HttpBaseServlet;
 import org.openbravo.base.secureApp.VariablesSecureApp;
 import org.openbravo.dal.core.OBContext;
@@ -138,7 +138,7 @@
     ActivationKey ak = ActivationKey.getInstance(true);
     if (ak.isActive()) {
       String hql = "from ADPreference pref where searchKey like :value and property = :prop and (visibleAtClient is null or visibleAtClient.id = '0')";
-      Query q = OBDal.getInstance().getSession().createQuery(hql);
+      Query<Object> q = OBDal.getInstance().getSession().createQuery(hql, Object.class);
       q.setParameter("value", "N");
       q.setParameter("prop", GOOGLE_PREFERENCE_PROPERTY);
 
--- a/src/org/openbravo/erpCommon/utility/CashVATUtil.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/erpCommon/utility/CashVATUtil.java	Tue Jul 24 10:44:21 2018 +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-2017 Openbravo SLU
+ * All portions are Copyright (C) 2013-2018 Openbravo SLU
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -30,9 +30,9 @@
 
 import org.apache.commons.lang.StringUtils;
 import org.apache.log4j.Logger;
-import org.hibernate.Query;
 import org.hibernate.Session;
 import org.hibernate.criterion.Restrictions;
+import org.hibernate.query.Query;
 import org.openbravo.base.provider.OBProvider;
 import org.openbravo.base.session.OBPropertiesProvider;
 import org.openbravo.dal.core.OBContext;
@@ -320,7 +320,7 @@
       hql.append(" and itcv.isManualSettlement = true ");
 
       final Session session = OBDal.getInstance().getSession();
-      final Query query = session.createQuery(hql.toString());
+      final Query<String> query = session.createQuery(hql.toString(), String.class);
       query.setParameter("invoiceId", invoice.getId());
       query.setMaxResults(1);
 
@@ -369,12 +369,12 @@
       hql.append(" and coalesce(itcv." + InvoiceTaxCashVAT_V.PROPERTY_CANCELED + ", 'N') = 'N' ");
 
       final Session session = OBDal.getInstance().getSession();
-      final Query query = session.createQuery(hql.toString());
+      final Query<Object[]> query = session.createQuery(hql.toString(), Object[].class);
       query.setParameter("cInvoiceTaxID", cInvoiceTaxID);
 
       final Map<String, BigDecimal> result = new HashMap<String, BigDecimal>();
 
-      final Object[] o = (Object[]) query.uniqueResult();
+      final Object[] o = query.uniqueResult();
       result.put("percentage", (BigDecimal) o[0]);
       result.put("taxableAmt", (BigDecimal) o[1]);
       result.put("taxAmt", (BigDecimal) o[2]);
@@ -407,10 +407,10 @@
           + InvoiceTaxCashVAT_V.PROPERTY_INVOICE + "." + Invoice.PROPERTY_ID);
 
       final Session session = OBDal.getInstance().getSession();
-      final Query query = session.createQuery(hql.toString());
+      final Query<BigDecimal> query = session.createQuery(hql.toString(), BigDecimal.class);
       query.setParameter("taxId", cTaxID);
       query.setParameter("invoiceId", cInvoiceId);
-      final BigDecimal percentage = (BigDecimal) query.uniqueResult();
+      final BigDecimal percentage = query.uniqueResult();
       return percentage == null ? BigDecimal.ZERO : percentage;
     } finally {
       OBContext.restorePreviousMode();
--- a/src/org/openbravo/erpCommon/utility/DimensionDisplayUtility.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/erpCommon/utility/DimensionDisplayUtility.java	Tue Jul 24 10:44:21 2018 +0200
@@ -25,9 +25,9 @@
 import java.util.Map;
 
 import org.apache.log4j.Logger;
-import org.hibernate.Query;
 import org.hibernate.Session;
 import org.hibernate.criterion.Restrictions;
+import org.hibernate.query.Query;
 import org.openbravo.base.provider.OBProvider;
 import org.openbravo.client.application.Parameter;
 import org.openbravo.client.application.Process;
@@ -196,10 +196,9 @@
       hql.append(" from " + DimensionMapping.ENTITY_NAME + " as dm ");
       hql.append(" where dm." + DimensionMapping.PROPERTY_TABLE + ".id = :tableId ");
       hql.append("       and dm." + DimensionMapping.PROPERTY_ACCOUNTINGDIMENSION + " = :dimension");
-      final Query queryLevel = session.createQuery(hql.toString());
+      final Query<String> queryLevel = session.createQuery(hql.toString(), String.class);
       queryLevel.setParameter("tableId", tableId);
       queryLevel.setParameter("dimension", dimension);
-      @SuppressWarnings("unchecked")
       List<String> levelList = queryLevel.list();
       int size = levelList.size();
       if (size == 0) {
@@ -402,9 +401,8 @@
    *          Field.
    * @return List of session variables required for computing the display logic of the field.
    */
-  @SuppressWarnings("unchecked")
   public static List<String> getRequiredSessionVariablesForTab(Tab tab, Field field) {
-    List<String> sessionVariables = new ArrayList<String>();
+    List<String> sessionVariables = new ArrayList<>();
     if (columnDimensionMap == null) {
       initialize();
     }
@@ -440,14 +438,14 @@
       hql.append(" where dm." + DimensionMapping.PROPERTY_TABLE + ".id = :tableId ");
       hql.append("       and dm." + DimensionMapping.PROPERTY_ACCOUNTINGDIMENSION + " = :dimension");
 
-      final Query queryDoc = session.createQuery(String.format(hql.toString(),
-          DimensionMapping.PROPERTY_DOCUMENTCATEGORY));
+      final Query<String> queryDoc = session.createQuery(
+          String.format(hql.toString(), DimensionMapping.PROPERTY_DOCUMENTCATEGORY), String.class);
       queryDoc.setParameter("tableId", tableId);
       queryDoc.setParameter("dimension", dimension);
       List<String> docBaseTypeList = queryDoc.list();
 
-      final Query queryLevel = session.createQuery(String.format(hql.toString(),
-          DimensionMapping.PROPERTY_LEVEL));
+      final Query<String> queryLevel = session.createQuery(
+          String.format(hql.toString(), DimensionMapping.PROPERTY_LEVEL), String.class);
       queryLevel.setParameter("tableId", tableId);
       queryLevel.setParameter("dimension", dimension);
       List<String> levelList = queryLevel.list();
@@ -459,7 +457,7 @@
       }
     } catch (Exception e) {
       log4j.error("Not possible to load session variables for tab: " + tab.getId(), e);
-      return new ArrayList<String>();
+      return new ArrayList<>();
     } finally {
       OBContext.restorePreviousMode();
     }
@@ -475,7 +473,7 @@
    *         configurable in client window and with corresponding value ('Y', 'N').
    */
   public static Map<String, String> getReadOnlyLogicSessionVariables() {
-    Map<String, String> sessionVariablesMap = new HashMap<String, String>();
+    Map<String, String> sessionVariablesMap = new HashMap<>();
     try {
       OBContext.setAdminMode(true);
       StringBuilder hql = new StringBuilder();
@@ -487,11 +485,8 @@
       hql.append(" group by dm." + DimensionMapping.PROPERTY_ACCOUNTINGDIMENSION + ", ");
       hql.append("          dm." + DimensionMapping.PROPERTY_LEVEL);
 
-      final Query queryRO = session.createQuery(hql.toString());
-      @SuppressWarnings("unchecked")
-      List<Object[]> readOnlyList = queryRO.list();
-
-      for (Object[] ro : readOnlyList) {
+      final Query<Object[]> queryRO = session.createQuery(hql.toString(), Object[].class);
+      for (Object[] ro : queryRO.list()) {
         String dim = (String) ro[0];
         String level = (String) ro[1];
         boolean isMandatory = (Boolean) ro[2];
@@ -502,14 +497,13 @@
           .error(
               "Not possible to load session variables for read only logic based on dimension mapping table",
               e);
-      return new HashMap<String, String>();
+      return new HashMap<>();
     } finally {
       OBContext.restorePreviousMode();
     }
     return sessionVariablesMap;
   }
 
-  @SuppressWarnings("unchecked")
   public static List<Object[]> getGroupDimensionMapping(List<String> dimensionList) {
     try {
       OBContext.setAdminMode(true);
@@ -523,13 +517,13 @@
       hql.append(" group by dm." + DimensionMapping.PROPERTY_ACCOUNTINGDIMENSION + ", ");
       hql.append("          dm." + DimensionMapping.PROPERTY_DOCUMENTCATEGORY);
 
-      final Query q = session.createQuery(hql.toString());
+      final Query<Object[]> q = session.createQuery(hql.toString(), Object[].class);
       q.setParameterList("dimensionList", dimensionList);
       return q.list();
 
     } catch (Exception e) {
       log4j.error("Error on getGroupDimensionMapping", e);
-      return new ArrayList<Object[]>();
+      return new ArrayList<>();
     } finally {
       OBContext.restorePreviousMode();
     }
@@ -576,9 +570,8 @@
    * @param parameter
    *          Parameter of Process Definition
    */
-  @SuppressWarnings("unchecked")
   public static List<String> getRequiredSessionVariablesForTab(Process process, Parameter parameter) {
-    List<String> sessionVariables = new ArrayList<String>();
+    List<String> sessionVariables = new ArrayList<>();
     if (columnDimensionMap == null) {
       initialize();
     }
@@ -593,7 +586,7 @@
       if (ADD_TRANSACTION_PROCESS_ID.equals(process.getId())) {
         tableId = FIN_FINACC_TRANSACTION_TABLE_ID;
       } else {
-        return new ArrayList<String>();
+        return new ArrayList<>();
       }
       final String columnName = parameter.getDBColumnName();
       String dimension = columnDimensionMap.get(columnName.toUpperCase());
@@ -618,14 +611,14 @@
       hql.append(" where dm." + DimensionMapping.PROPERTY_TABLE + ".id = :tableId ");
       hql.append("       and dm." + DimensionMapping.PROPERTY_ACCOUNTINGDIMENSION + " = :dimension");
 
-      final Query queryDoc = session.createQuery(String.format(hql.toString(),
-          DimensionMapping.PROPERTY_DOCUMENTCATEGORY));
+      final Query<String> queryDoc = session.createQuery(
+          String.format(hql.toString(), DimensionMapping.PROPERTY_DOCUMENTCATEGORY), String.class);
       queryDoc.setParameter("tableId", tableId);
       queryDoc.setParameter("dimension", dimension);
       List<String> docBaseTypeList = queryDoc.list();
 
-      final Query queryLevel = session.createQuery(String.format(hql.toString(),
-          DimensionMapping.PROPERTY_LEVEL));
+      final Query<String> queryLevel = session.createQuery(
+          String.format(hql.toString(), DimensionMapping.PROPERTY_LEVEL), String.class);
       queryLevel.setParameter("tableId", tableId);
       queryLevel.setParameter("dimension", dimension);
       List<String> levelList = queryLevel.list();
@@ -637,7 +630,7 @@
       }
     } catch (Exception e) {
       log4j.error("Not possible to load session variables for process: " + process.getId(), e);
-      return new ArrayList<String>();
+      return new ArrayList<>();
     } finally {
       OBContext.restorePreviousMode();
     }
@@ -703,10 +696,9 @@
       hql.append(" from " + DimensionMapping.ENTITY_NAME + " as dm ");
       hql.append(" where dm." + DimensionMapping.PROPERTY_TABLE + ".id = :tableId ");
       hql.append("       and dm." + DimensionMapping.PROPERTY_ACCOUNTINGDIMENSION + " = :dimension");
-      final Query queryLevel = session.createQuery(hql.toString());
+      final Query<String> queryLevel = session.createQuery(hql.toString(), String.class);
       queryLevel.setParameter("tableId", tableId);
       queryLevel.setParameter("dimension", dimension);
-      @SuppressWarnings("unchecked")
       List<String> levelList = queryLevel.list();
       int size = levelList.size();
       if (size == 0) {
--- a/src/org/openbravo/erpCommon/utility/OBLedgerUtils.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/erpCommon/utility/OBLedgerUtils.java	Tue Jul 24 10:44:21 2018 +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) 2016 Openbravo SLU
+ * All portions are Copyright (C) 2016-2018 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -22,7 +22,7 @@
 
 import org.apache.commons.lang.StringUtils;
 import org.apache.log4j.Logger;
-import org.hibernate.Query;
+import org.hibernate.query.Query;
 import org.openbravo.dal.core.OBContext;
 import org.openbravo.dal.security.OrganizationStructureProvider;
 import org.openbravo.dal.service.OBDal;
@@ -122,7 +122,8 @@
     where.append(" from " + AcctSchema.ENTITY_NAME);
     where.append(" where " + AcctSchema.PROPERTY_CLIENT + ".id = :clientId");
     where.append(" order by " + AcctSchema.PROPERTY_NAME);
-    Query qry = OBDal.getInstance().getSession().createQuery(where.toString());
+    Query<String> qry = OBDal.getInstance().getSession()
+        .createQuery(where.toString(), String.class);
     qry.setParameter("clientId", clientId);
     qry.setMaxResults(1);
     return (String) qry.uniqueResult();
--- a/src/org/openbravo/erpCommon/utility/SystemInfo.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/erpCommon/utility/SystemInfo.java	Tue Jul 24 10:44:21 2018 +0200
@@ -53,9 +53,9 @@
 
 import org.apache.log4j.Logger;
 import org.codehaus.jettison.json.JSONArray;
-import org.hibernate.Query;
 import org.hibernate.criterion.Order;
 import org.hibernate.criterion.Restrictions;
+import org.hibernate.query.Query;
 import org.openbravo.base.ServerVersionChecker;
 import org.openbravo.base.session.OBPropertiesProvider;
 import org.openbravo.dal.core.OBContext;
@@ -647,9 +647,10 @@
     hql.append("       max(s.creationDate) as lastLogin, ");
     hql.append("       count(*) as totalLogins");
     hql.append("  from ADSession s");
-    Query q = OBDal.getInstance().getSession().createQuery(hql.toString());
+    Query<Object[]> q = OBDal.getInstance().getSession()
+        .createQuery(hql.toString(), Object[].class);
     if (q.list().size() != 0) {
-      Object[] logInfo = (Object[]) q.list().get(0);
+      Object[] logInfo = q.list().get(0);
       firstLogin = (Date) logInfo[0];
       lastLogin = (Date) logInfo[1];
       numberOfLogins = (Long) logInfo[2];
@@ -777,7 +778,6 @@
 
   }
 
-  @SuppressWarnings("unchecked")
   private static List<Long> getWsLogins(String type, Date fromDate) {
     StringBuilder hql = new StringBuilder();
     hql.append("select count(*)\n");
@@ -785,7 +785,7 @@
     hql.append(" where loginStatus = :type\n");
     hql.append("   and creationDate > :firstDay\n");
     hql.append(" group by day(creationDate), month(creationDate), year(creationDate)\n");
-    Query qWs = OBDal.getInstance().getSession().createQuery(hql.toString());
+    Query<Long> qWs = OBDal.getInstance().getSession().createQuery(hql.toString(), Long.class);
     qWs.setParameter("firstDay", fromDate);
     qWs.setParameter("type", type);
     return qWs.list();
--- a/src/org/openbravo/erpCommon/utility/TreeUtility.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/erpCommon/utility/TreeUtility.java	Tue Jul 24 10:44:21 2018 +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) 2012 Openbravo SLU
+ * All portions are Copyright (C) 2012-2018 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -26,7 +26,7 @@
 import java.util.Set;
 
 import org.apache.log4j.Logger;
-import org.hibernate.Query;
+import org.hibernate.query.Query;
 import org.openbravo.dal.core.OBContext;
 import org.openbravo.dal.core.SessionHandler;
 import org.openbravo.model.ad.utility.Tree;
@@ -35,8 +35,8 @@
 public class TreeUtility {
   private static final Logger log4j = Logger.getLogger(TreeUtility.class);
 
-  private Map<String, Set<String>> childTrees = new HashMap<String, Set<String>>();
-  private Map<String, Set<String>> naturalTrees = new HashMap<String, Set<String>>();
+  private Map<String, Set<String>> childTrees = new HashMap<>();
+  private Map<String, Set<String>> naturalTrees = new HashMap<>();
 
   /**
    * Gets Natural tree for the given node
@@ -45,10 +45,10 @@
     initialize(treeType);
     Set<String> result;
     if (naturalTrees.get(nodeId) == null) {
-      result = new HashSet<String>();
+      result = new HashSet<>();
       result.add(nodeId);
     } else {
-      result = new HashSet<String>(naturalTrees.get(nodeId));
+      result = new HashSet<>(naturalTrees.get(nodeId));
     }
     log4j.debug("Natural Tree(" + treeType + ") for the node" + nodeId + ":" + result.toString());
     return result;
@@ -60,7 +60,7 @@
   public Set<String> getChildTree(String nodeId, String treeType, boolean includeNode) {
     initialize(treeType);
     Set<String> childNode = this.getChildNode(nodeId, treeType);
-    Set<String> result = new HashSet<String>();
+    Set<String> result = new HashSet<>();
 
     if (includeNode)
       result.add(nodeId);
@@ -81,9 +81,9 @@
   public Set<String> getChildNode(String nodeId, String treeType) {
     initialize(treeType);
     if (childTrees.get(nodeId) == null) {
-      return new HashSet<String>();
+      return new HashSet<>();
     } else {
-      return new HashSet<String>(childTrees.get(nodeId));
+      return new HashSet<>(childTrees.get(nodeId));
     }
   }
 
@@ -92,21 +92,20 @@
     final String clientId = OBContext.getOBContext().getCurrentClient().getId();
     final String qryStr = "select t from " + Tree.class.getName() + " t where treetype='"
         + treeType + "' and client.id='" + clientId + "'";
-    final Query qry = SessionHandler.getInstance().createQuery(qryStr);
+    final Query<Tree> qry = SessionHandler.getInstance().createQuery(qryStr, Tree.class);
+    final List<Tree> ts = qry.list();
 
-    @SuppressWarnings("unchecked")
-    final List<Tree> ts = qry.list();
-    final List<TreeNode> treeNodes = new ArrayList<TreeNode>();
+    final List<TreeNode> treeNodes = new ArrayList<>();
     for (final Tree t : ts) {
       final String nodeQryStr = "select tn from " + TreeNode.class.getName()
           + " tn where tn.tree.id='" + t.getId() + "'";
-      final Query nodeQry = SessionHandler.getInstance().createQuery(nodeQryStr);
-      @SuppressWarnings("unchecked")
+      final Query<TreeNode> nodeQry = SessionHandler.getInstance().createQuery(nodeQryStr,
+          TreeNode.class);
       final List<TreeNode> tns = nodeQry.list();
       treeNodes.addAll(tns);
     }
 
-    final List<Node> nodes = new ArrayList<Node>(treeNodes.size());
+    final List<Node> nodes = new ArrayList<>(treeNodes.size());
     for (final TreeNode tn : treeNodes) {
       final Node on = new Node();
       on.setTreeNode(tn);
@@ -120,7 +119,7 @@
     for (final Node on : nodes) {
       naturalTrees.put(on.getTreeNode().getNode(), on.getNaturalTree());
       if (on.getChildren() != null) {
-        Set<String> os = new HashSet<String>();
+        Set<String> os = new HashSet<>();
         for (Node o : on.getChildren())
           os.add(o.getTreeNode().getNode());
         childTrees.put(on.getTreeNode().getNode(), os);
@@ -133,7 +132,7 @@
 
   private TreeNode treeNode;
   private Node parent;
-  private List<Node> children = new ArrayList<Node>();
+  private List<Node> children = new ArrayList<>();
 
   private Set<String> naturalTreeParent = null;
   private Set<String> naturalTreeChildren = null;
@@ -158,7 +157,7 @@
 
   public Set<String> getNaturalTree() {
     if (naturalTree == null) {
-      naturalTree = new HashSet<String>();
+      naturalTree = new HashSet<>();
       naturalTree.add(getTreeNode().getNode());
       if (getParent() != null) {
         getParent().getParentPath(naturalTree);
@@ -172,7 +171,7 @@
 
   public void getParentPath(Set<String> theNaturalTree) {
     if (naturalTreeParent == null) {
-      naturalTreeParent = new HashSet<String>();
+      naturalTreeParent = new HashSet<>();
       naturalTreeParent.add(getTreeNode().getNode());
       if (getParent() != null) {
         getParent().getParentPath(naturalTreeParent);
@@ -183,7 +182,7 @@
 
   public void getChildPath(Set<String> theNaturalTree) {
     if (naturalTreeChildren == null) {
-      naturalTreeChildren = new HashSet<String>();
+      naturalTreeChildren = new HashSet<>();
       naturalTreeChildren.add(getTreeNode().getNode());
       for (final Node child : getChildren()) {
         child.getChildPath(naturalTreeChildren);
--- a/src/org/openbravo/erpCommon/utility/Utility.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/erpCommon/utility/Utility.java	Tue Jul 24 10:44:21 2018 +0200
@@ -61,7 +61,7 @@
 import org.apache.commons.lang.StringEscapeUtils;
 import org.apache.commons.lang.StringUtils;
 import org.apache.log4j.Logger;
-import org.hibernate.Query;
+import org.hibernate.query.Query;
 import org.openbravo.base.HttpBaseServlet;
 import org.openbravo.base.exception.OBException;
 import org.openbravo.base.provider.OBConfigFileProvider;
@@ -1851,7 +1851,7 @@
         + "      ADListTrl rlt" + " where rl.reference = r" + "  and rlt.listReference = rl"
         + "  and rlt.language.language = '" + lang + "'" + "  and r.name =  '" + ListName + "'"
         + "  and rl.searchKey = '" + value + "'";
-    Query q = OBDal.getInstance().getSession().createQuery(hql);
+    Query<String> q = OBDal.getInstance().getSession().createQuery(hql, String.class);
     q.setMaxResults(1);
     String name = (String) q.uniqueResult();
     if (name != null) {
@@ -1862,7 +1862,7 @@
     hql = "  select rl.name " + " from ADReference r, " + "      ADList rl"
         + " where rl.reference = r" + "  and r.name =  '" + ListName + "'"
         + "  and rl.searchKey = '" + value + "'";
-    q = OBDal.getInstance().getSession().createQuery(hql);
+    q = OBDal.getInstance().getSession().createQuery(hql, String.class);
     q.setMaxResults(1);
     name = (String) q.uniqueResult();
     if (name != null) {
@@ -2464,7 +2464,8 @@
     hql.append("       f.name\n");
     hql.append("  from ADField f\n");
     hql.append(" where f.id =:fieldId\n");
-    Query qName = OBDal.getInstance().getSession().createQuery(hql.toString());
+    Query<Object[]> qName = OBDal.getInstance().getSession()
+        .createQuery(hql.toString(), Object[].class);
     qName.setParameter("lang", language);
     qName.setParameter("fieldId", fieldId);
 
@@ -2473,7 +2474,7 @@
       return "";
     }
 
-    Object[] names = (Object[]) qName.list().get(0);
+    Object[] names = qName.list().get(0);
     return names[0] != null ? (String) names[0] : (String) names[1];
   }
 
--- a/src/org/openbravo/event/CharacteristicValueEventHandler.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/event/CharacteristicValueEventHandler.java	Tue Jul 24 10:44:21 2018 +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-2015 Openbravo SLU
+ * All portions are Copyright (C) 2013-2018 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  *************************************************************************
@@ -24,8 +24,9 @@
 
 import org.apache.commons.lang.StringUtils;
 import org.apache.log4j.Logger;
-import org.hibernate.Query;
 import org.hibernate.Session;
+import org.hibernate.query.Query;
+import org.hibernate.resource.transaction.spi.TransactionStatus;
 import org.openbravo.base.model.Entity;
 import org.openbravo.base.model.ModelProvider;
 import org.openbravo.base.model.Property;
@@ -83,6 +84,7 @@
       where.append(")");
       try {
         final Session session = OBDal.getInstance().getSession();
+        @SuppressWarnings("rawtypes")
         final Query charConfQuery = session.createQuery(where.toString());
         charConfQuery.setParameter("user", OBContext.getOBContext().getUser());
         charConfQuery.setParameter("characteristicValue", chv);
@@ -100,7 +102,8 @@
   public void onTransactionCompleted(@Observes TransactionCompletedEvent event) {
     String strChValueId = chvalueUpdated.get();
     chvalueUpdated.set(null);
-    if (StringUtils.isBlank(strChValueId) || event.getTransaction().wasRolledBack()) {
+    if (StringUtils.isBlank(strChValueId)
+        || event.getTransaction().getStatus() == TransactionStatus.ROLLED_BACK) {
       return;
     }
     try {
--- a/src/org/openbravo/event/ConversionRateEventHandler.java	Tue Jul 24 10:39:37 2018 +0200
+++ b/src/org/openbravo/event/ConversionRateEventHandler.java	Tue Jul 24 10:44:21 2018 +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-2016 Openbravo SLU 
+ * All portions are Copyright (C) 2015-2018 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -22,7 +22,7 @@
 
 import javax.enterprise.event.Observes;
 
-import org.hibernate.Query;
+import org.hibernate.query.Query;
 import org.openbravo.base.exception.OBException;
 import org.openbravo.base.model.Entity;
 import org.openbravo.base.model.ModelProvider;
@@ -48,8 +48,7 @@
     return entities;
   }
 
-  public void onNew(@Observes
-  EntityNewEvent event) {
+  public void onNew(@Observes EntityNewEvent event) {
     if (!isValidEvent(event)) {
       return;
     }
@@ -63,8 +62,7 @@
     }
   }