0

I have one existing method which is using Hibernate query to fetch the data from DB.Query is created based on IF Else Condition. How to convert the query to a parameterized query.

working Code is as :

Session session = getCurrentSession();
        List<Configuration> results = new ArrayList<>();
        try {
            String hql = "from PaymentConfiguration where activeIndicator = 'Y' AND (countryCode = null OR countryCode = '" + countryCode+ "')" ;
            if (null != currencyCode && !(currencyCode.isEmpty())) {
                hql += " AND ( billingCurrencyCode = null OR billingCurrencyCode = '" + currencyCode + "')";
            }
            if (null != paymentCategory && !(paymentCategory.isEmpty())) {
                hql += " AND paymentCategory = '" + paymentCategory + "'";
            }
            if (null != paymentType && !(paymentType.isEmpty())) {
                hql += " AND paymentType = '" + paymentType + "'";
            }
            if(null!= region && (region.equalsIgnoreCase("Domestic"))){
                hql += " AND vendorId in("v1,v2,v3")";
            }
            else
            {
                hql+=" AND vendorId in ("v1,v3,v4")";
            }

            results = session.createQuery(hql).list();  

As I know I can use setParameter("countryCode", countryCode) but how to use it in if else condition to cover all scenario. Or is there any other way to achieve this.

Vipul Singh
  • 393
  • 9
  • 26
  • If you want to stick with Hibernate you should use Criteria API https://docs.jboss.org/hibernate/orm/5.4/userguide/html_single/Hibernate_User_Guide.html#criteria or if you don't must use Hibernate have a look at https://jooq.org – Simon Martinelli Jun 19 '20 at 15:02
  • Another option is FluentJPA - https://github.com/streamx-co/FluentJPA/wiki/Dynamic-Queries – Konstantin Triger Jun 21 '20 at 09:42

0 Answers0