gif animé ordinateur

mercredi 11 septembre 2013

Hibernate Criteria, Duplicate Alias and Restrictions

I want to share this snippet with all whom it may concern.It seems important and useful.
During my recent Java developments, I tried to expand dynamically, one Hiernate-criteria object with an unknown in advance restrictions or joins. So before adding any, my program is to verify whether or not this join, its aliase are or not already added, if this is not the case, then it is added.

This is the code snippet :

private String createAliasIfNotAlreadyExist(Criteria criteria,String associationPath, String newAlias) {  CriteriaImpl criteriaImpl = (CriteriaImpl)criteria;  @SuppressWarnings("unchecked")  Iterator<Subcriteria> it = criteriaImpl.iterateSubcriteria();  boolean aliasAlreadyExists = false;  String alias =null;  while(it.hasNext()){      Subcriteria subCriteria = it.next();    if (associationPath.equals(subCriteria.getPath())) {// identifie la jointure sur l'objet     aliasAlreadyExists = true;     alias = subCriteria.getAlias();// l'alias     //System.out.println("associationPath : '" + associationPath+"' already exist with alias = '" + alias+"'");     break;    }  }    if(!aliasAlreadyExists){   //System.out.println("associationPath : '"+associationPath+"' doesn't exists ");   criteria.createAlias(associationPath, newAlias,CriteriaSpecification.LEFT_JOIN);   criteria.setFetchMode(associationPath, FetchMode.JOIN);   alias= newAlias;   //System.out.println("new one is created");    }    return alias; }

private void addRestrictionIfNotAlreadyExists(Criteria criteria, Criterion restriction) { CriteriaImpl criteriaImpl = (CriteriaImpl)criteria;   @SuppressWarnings("unchecked")   Iterator<CriterionEntry> itit = criteriaImpl.iterateExpressionEntries();   boolean expressionAlreadyExist = false;   while (itit.hasNext()) {     CriterionEntry criterionEntry = itit.next();     Criterion cc = criterionEntry.getCriterion();      if(cc.toString().equals(restriction.toString())){      expressionAlreadyExist=true;      break;     }   }   if(!expressionAlreadyExist){   System.out.println("RESTRICTION '"+restriction+"' IS ADDED TO CRITERIA");    criteria.add(restriction);   }else{    System.out.println("CRITERIA ALREADY CONTAINS RESTRICTION : '"+restriction+"'");   } }


1 commentaire: