Hibernate Criteria – SELECT DISTINCT and while loop (A[i] && B[i]) || (A[i+1] && B[i+1])
Here is the case: I need to get the distinct SX-Number from list of shipment of each shipment data of selected HUB, on SoftONE Logistic Database using Hibernate Criteria.
The scenario will be:
- User will select the HUB from combo box UI element
- From selected HUB, system will pick up the JCode Name and Consignee Account
- Using those destination and consignee account data, system will retrieve the shipment data
- On the shipment data, there is SX-Number data
- System need to list unique SX-Number from the filtered shipment data
Here is the implementation of the scenario above, skip the getting hub data from UI
// Open Hibernate Session
sessionFactory.getCurrentSession().beginTransaction();
// Based on selected HUB, system will retrieve
Criteria jCodeCriteria = sessionFactory.getCurrentSession().createCriteria(MasterJCode.class);
if(category.compareToIgnoreCase("HUB") == 0){
jCodeCriteria.add(Restrictions.eq("destination", value));
}
listJCode = jCodeCriteria.list();
// Check the list of jcode whether it is null or empty, if not continue the process
if((listJCode != null) && (listJCode.size()>0)){
// Create new criteria to get distinct SX-Number based on jcode name and consignee account stated above
Criteria fastCriteria = sessionFactory.getCurrentSession().createCriteria(FASTData.class);
// Implementation of SELECT DISTINCT(a.refDesc)
fastCriteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
fastCriteria.setProjection(Projections.distinct(Projections.property("refDesc")));
// implementation of WHERE while loop (A[i] && B[i]) || (A[i+1] && B[i+1])
// Use disjunction to implement OR logic between Restriction.and
Disjunction disjunction = Restrictions.disjunction();
// Use Restriction.and to implement (A[i] && B[ii])
for(MasterJCode masterJCode:listJCode){
disjunction.add(Restrictions.and(Restrictions.eq("destination", masterJCode.getJcodeName()), Restrictions.eq("consigneeAccount", masterJCode.getConsigneeAccount())));
}
fastCriteria.add(disjunction);
// Execute the criteria
List data = fastCriteria.list();
You will get the list of OBJECT as a result. Here is the thing, even though in the beginning of Criteria, the used
Criteria fastCriteria = sessionFactory.getCurrentSession().createCriteria(FASTData.class);
Logically the result will be list of FASTData, and we will use for loop to retrieve FASTData object from the result list. Since in the criteria, there is no method .iterate() unlike query, we can not use iterator to iterate the list of object. We will use for loop instead
for(Object obj:data){
System.out.println(String.valueOf(obj));
}
Lastly, commit the transaction
sessionFactory.getCurrentSession().getTransaction().commit();