package org.openlmis.referencedata.repository.custom.impl;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.openlmis.referencedata.domain.Facility;
import org.openlmis.referencedata.repository.custom.FacilityRepositoryCustom;

import java.util.List;

public class FacilityRepositoryImpl implements FacilityRepositoryCustom {

  @PersistenceContext
  private EntityManager entityManager;


  /**
   * This method is supposed to retrieve all Facilities with facilityCode similar to
   * code parameter or facilityName similar to name parameter.
   * To find all wanted Facilities we use criteria query and like operator.
   *
   * @param code Part of wanted code.
   * @param name Part of wanted name.
   * @return List of Facilities with wanted code or name.
   */
  public List<Facility> findFacilitiesByCodeOrName(String code, String name) {
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Facility> query = builder.createQuery(Facility.class);
    Root<Facility> root = query.from(Facility.class);
    Predicate predicate = builder.conjunction();
    if (code != null) {
      Predicate codeOrNamePredicate = builder.or(
          builder.like(
              root.get("code"), "%" + code + "%"),
          builder.like(
              root.get("name"), "%" + name + "%"));
      predicate = builder.and(
          predicate, codeOrNamePredicate);
    }
    query.where(predicate);
    return entityManager.createQuery(query).getResultList();
  }

}

@@ -53,16 +53,170 @@
 .impl;%0A%0A
+import org.openlmis.referencedata.domain.Facility;%0Aimport org.openlmis.referencedata.repository.custom.FacilityRepositoryCustom;%0A%0Aimport java.util.List;%0A%0A
 import j
@@ -480,161 +480,8 @@
 oot;
-%0Aimport org.openlmis.referencedata.domain.Facility;%0Aimport org.openlmis.referencedata.repository.custom.FacilityRepositoryCustom;%0A%0Aimport java.util.List;
 %0A%0Apu
@@ -1301,11 +1301,11 @@
 der.
-con
+dis
 junc
@@ -1308,24 +1308,25 @@
 junction();%0A
+%0A
     if (code
@@ -1347,29 +1347,9 @@
     
-Predicate codeOrNameP
+p
 redi
@@ -1366,26 +1366,26 @@
 lder.or(
-%0A         
+predicate,
  builder
@@ -1386,39 +1386,24 @@
 uilder.like(
-%0A              
 root.get(%22co
@@ -1429,157 +1429,130 @@
 %22%25%22)
-,
+);
 %0A    
-  
+%7D%0A%0A
     
-builder.like(%0A              root.get(%22name%22), %22%25%22 + name + %22%25%22));%0A      predicate = builder.and(%0A          predicate, codeOrNamePredicate
+if (name != null) %7B%0A      predicate = builder.or(predicate, builder.like(root.get(%22name%22), %22%25%22 + name + %22%25%22)
 );%0A 
@@ -1556,16 +1556,17 @@
 ;%0A    %7D%0A
+%0A
     quer

Fix search faclility by code or name