Example usage for org.hibernate.criterion CriteriaSpecification DISTINCT_ROOT_ENTITY

List of usage examples for org.hibernate.criterion CriteriaSpecification DISTINCT_ROOT_ENTITY

Introduction

In this page you can find the example usage for org.hibernate.criterion CriteriaSpecification DISTINCT_ROOT_ENTITY.

Prototype

ResultTransformer DISTINCT_ROOT_ENTITY

To view the source code for org.hibernate.criterion CriteriaSpecification DISTINCT_ROOT_ENTITY.

Click Source Link

Document

Each row of results is a distinct instance of the root entity

Usage

From source file:edu.duke.cabig.c3pr.dao.HealthcareSiteDao.java

License:BSD License

/**
  * Search by example./*from   ww w  .  jav a 2 s.  c  o  m*/
  * 
  * @param hcs the hcs
  * @param isWildCard the is wild card
  * @return the list< healthcare site>
  */

public List<HealthcareSite> searchByExample(HealthcareSite hcs, boolean isWildCard, int maxResults) {

    List<HealthcareSite> remoteHealthcareSites = new ArrayList<HealthcareSite>();
    remoteHealthcareSites.addAll(getExternalOrganizationsByExampleFromResolver(hcs));
    updateDatabaseWithRemoteHealthcareSites(remoteHealthcareSites);

    List<HealthcareSite> result = new ArrayList<HealthcareSite>();
    Example example = Example.create(hcs).excludeZeroes().ignoreCase();
    try {
        Criteria orgCriteria = getHibernateTemplate().getSessionFactory().getCurrentSession()
                .createCriteria(HealthcareSite.class);
        Criteria identifiersAssignedToOrganizationCriteria = orgCriteria
                .createCriteria("identifiersAssignedToOrganization");

        if (StringUtils.isNotBlank(hcs.getPrimaryIdentifier())) {
            identifiersAssignedToOrganizationCriteria
                    .add(Expression.ilike("value", "%" + hcs.getPrimaryIdentifier() + "%"));
            identifiersAssignedToOrganizationCriteria
                    .add(Expression.eq("typeInternal", OrganizationIdentifierTypeEnum.CTEP.getName()));
        }
        if (StringUtils.isNotBlank(hcs.getName())) {
            orgCriteria.add(Expression.ilike("name", "%" + hcs.getName() + "%"));
        }

        if (isWildCard) {
            example.enableLike(MatchMode.ANYWHERE);
        }
        example.excludeProperty("studyEndPointProperty");
        example.excludeProperty("registrationEndPointProperty");

        orgCriteria.addOrder(Order.asc("name"));
        orgCriteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
        if (maxResults > 0)
            orgCriteria.setMaxResults(maxResults);
        result = orgCriteria.add(example).list();
    } catch (Exception e) {
        log.error(e.getMessage());
    }
    return result;
}

From source file:edu.duke.cabig.c3pr.dao.ICD9DiseaseSiteDao.java

License:BSD License

public List<ICD9DiseaseSite> getAllOrderedByName() {
    Criteria icdDiseaseSiteCriteria = getSession().createCriteria(ICD9DiseaseSite.class);
    icdDiseaseSiteCriteria.addOrder(Order.asc("name"));
    icdDiseaseSiteCriteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
    return icdDiseaseSiteCriteria.list();
}

From source file:edu.duke.cabig.c3pr.dao.InvestigatorDao.java

License:BSD License

public List<Investigator> searchByExample(Investigator inv, boolean isWildCard) {
    RemoteInvestigator remoteInvestigator = convertToRemoteInvestigatorForCoppaQuery(inv);
    getRemoteInvestigatorsAndUpdateDatabase(remoteInvestigator);

    List<Investigator> result = new ArrayList<Investigator>();

    Example example = Example.create(inv).excludeZeroes().ignoreCase();
    try {/* w  w w . j ava2 s .c  o  m*/
        Criteria orgCriteria = getSession().createCriteria(Investigator.class);

        if (inv.getHealthcareSiteInvestigators() != null
                && inv.getHealthcareSiteInvestigators().get(0).getHealthcareSite() != null) {
            Criteria healthcareSiteInvestigatorCriteria = orgCriteria
                    .createCriteria("healthcareSiteInvestigatorsInternal");
            Criteria healthcareSiteCriteria = healthcareSiteInvestigatorCriteria
                    .createCriteria("healthcareSite");
            healthcareSiteCriteria.add(Expression.eq("id",
                    inv.getHealthcareSiteInvestigators().get(0).getHealthcareSite().getId()));
        }
        orgCriteria.addOrder(Order.asc("assignedIdentifier"));
        orgCriteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);

        if (isWildCard) {
            example.enableLike(MatchMode.ANYWHERE);
            orgCriteria.add(example);
            result = orgCriteria.list();
        } else {
            result = orgCriteria.add(example).list();
        }
    } catch (Exception e) {
        log.error(e.getMessage());
    }
    return result;
}

From source file:edu.duke.cabig.c3pr.dao.PersonUserDao.java

License:BSD License

/**
 * Search by example.//  ww  w .  j  ava  2  s .c  o  m
 *
 * @param personUser the staff
 * @param isWildCard the is wild card
 * @return the list
 */
public List<PersonUser> searchByExample(PersonUser personUser, boolean isWildCard, String emailAddress) {

    // get the remote staff and update the database first
    RemotePersonUser remotePersonUser = convertToRemotePersonUser(personUser);
    getRemoteResearchStaffFromResolverByExample(remotePersonUser);

    List<PersonUser> result = new ArrayList<PersonUser>();

    Example example = Example.create(personUser).excludeZeroes().ignoreCase();
    example.excludeProperty("salt");
    example.excludeProperty("passwordLastSet");
    try {
        Criteria criteria = getSession().createCriteria(PersonUser.class);
        criteria.addOrder(Order.asc("assignedIdentifier"));
        criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);

        if (isWildCard) {
            example.enableLike(MatchMode.ANYWHERE);
            criteria.add(example);
            if (personUser.getHealthcareSites().size() > 0) {
                criteria.createCriteria("healthcareSites").add(Restrictions.ilike("name",
                        "%" + personUser.getHealthcareSites().get(0).getName() + "%"));
                // As per discussion in search by example staff will have only one healthcare site
            }
            if (!StringUtils.isBlank(emailAddress)) {
                Criteria emailCriteria = criteria.createCriteria("contactMechanisms");
                emailCriteria.add(Restrictions.ilike("value", "%" + emailAddress + "%"));
                //emailCriteria.add(Restrictions.ilike("type", ContactMechanismType.EMAIL)); 
            }
            result = criteria.list();
        } else {
            result = criteria.add(example).list();
        }
    } catch (Exception e) {
        log.error(e.getMessage());
    }
    return result;
}

From source file:edu.duke.cabig.c3pr.dao.StudyDao.java

License:BSD License

/**
  * Search by example.//from www  . j a  v a  2s.  co m
  *                                                                                                                           
  * @param study the exmple study
  * @param isWildCard the wild card
  * @param maxResults the max results
  * @param order the order
  * @param orderBy the order by
  * 
  * @return the list< study>
  */
public List<Study> searchByExample(Study study, boolean isWildCard, int maxResults, String order,
        String orderBy) {
    List<Study> result = new ArrayList<Study>();

    Example example = Example.create(study).excludeZeroes().ignoreCase();
    Example subExample = Example.create(study.getStudyVersion()).excludeZeroes().ignoreCase();
    Criteria studyCriteria = getSession().createCriteria(Study.class);

    if ("ascending".equals(order)) {
        studyCriteria.addOrder(Order.asc(orderBy));
    } else if ("descending".equals(order)) {
        studyCriteria.addOrder(Order.desc(orderBy));
    }

    studyCriteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);

    if (maxResults > 0)
        studyCriteria.setMaxResults(maxResults);

    if (isWildCard) {
        example.excludeProperty("doNotUse").enableLike(MatchMode.ANYWHERE);
        subExample.excludeProperty("doNotUse").enableLike(MatchMode.ANYWHERE);
        //studyCriteria.add(example);
        //studyCriteria.createCriteria("studyVersionsInternal").add(subExample);
        if (study.getIdentifiers().size() > 1) {
            studyCriteria.createCriteria("identifiers")
                    .add(Restrictions.ilike("value", "%" + study.getIdentifiers().get(0).getValue() + "%"))
                    .add(Restrictions.ilike("value", "%" + study.getIdentifiers().get(1).getValue() + "%"));
        } else if (study.getIdentifiers().size() > 0) {
            studyCriteria.createCriteria("identifiers")
                    .add(Restrictions.ilike("value", "%" + study.getIdentifiers().get(0).getValue() + "%"));
        }
        //result = studyCriteria.list();
    }
    studyCriteria.createCriteria("studyVersionsInternal").add(subExample);
    result = studyCriteria.add(example).list();
    return result;

}

From source file:edu.duke.cabig.c3pr.dao.StudySubjectDao.java

License:BSD License

/**
 * *./*from   w  w  w .j  a v  a 2  s.  c o  m*/
 * 
 * @param registration
 *            the registration
 * @param isWildCard
 *            the is wild card
 * @param maxResults
 *            the max results
 * 
 * @return list of matching registration objects based on your sample
 *         registration object
 */
public List<StudySubject> searchByExample(StudySubject registration, boolean isWildCard, int maxResults) {
    List<StudySubject> result = new ArrayList<StudySubject>();

    Example example = Example.create(registration).excludeZeroes().ignoreCase();
    try {
        Criteria studySubjectCriteria = getSession().createCriteria(StudySubject.class);
        studySubjectCriteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);

        if (isWildCard) {
            example.excludeProperty("doNotUse").enableLike(MatchMode.ANYWHERE);
            studySubjectCriteria.add(example);

            if (maxResults > 0)
                studySubjectCriteria.setMaxResults(maxResults);

            if (registration.getIdentifiers().size() > 1) {
                studySubjectCriteria.createCriteria("identifiers")
                        .add(Restrictions.ilike("value",
                                "%" + registration.getIdentifiers().get(0).getValue() + "%"))
                        .add(Restrictions.ilike("value",
                                "%" + registration.getIdentifiers().get(1).getValue() + "%"));
            } else if (registration.getIdentifiers().size() > 0) {
                studySubjectCriteria.createCriteria("identifiers").add(Restrictions.ilike("value",
                        "%" + registration.getIdentifiers().get(0).getValue() + "%"));
            }
            result = studySubjectCriteria.list();
        }
        result = studySubjectCriteria.add(example).list();
    } catch (Exception e) {
        log.error(e.getMessage());
    }
    return result;
}

From source file:edu.duke.cabig.c3pr.dao.Summary3ReportDao.java

License:BSD License

public List<Summary3ReportDiseaseSite> getAllOrderedByName() {
    Criteria summary3ReportDiseaseSiteCriteria = getSession().createCriteria(Summary3ReportDiseaseSite.class);
    summary3ReportDiseaseSiteCriteria.addOrder(Order.asc("name"));
    summary3ReportDiseaseSiteCriteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
    return summary3ReportDiseaseSiteCriteria.list();
}

From source file:edu.ku.brc.specify.conversion.GenericDBConversion.java

License:Open Source License

/**
 * Convert all the biological attributes to Collection Object Attributes. Each old record may
 * end up being multiple records in the new schema. This will first figure out which columns in
 * the old schema were used and only map those columns to the new database.<br>
 * <br>//from   w w w  .j  a v  a2 s.  c  o m
 * It also will use the old name if there is not mapping for it. The old name is converted from
 * lower/upper case to be space separated where each part of the name starts with a capital
 * letter.
 * 
 * @param discipline the Discipline
 * @param colToNameMap a mape for old names to new names
 * @param typeMap a map for changing the type of the data (meaning an old value may be a boolean
 *            stored in a float)
 * @return true for success
 */
public boolean convertBiologicalAttrs(final Discipline discipline,
        @SuppressWarnings("unused") final Map<String, String> colToNameMap, final Map<String, Short> typeMap) {
    AttributeIFace.FieldType[] attrTypes = { AttributeIFace.FieldType.IntegerType,
            AttributeIFace.FieldType.FloatType, AttributeIFace.FieldType.DoubleType,
            AttributeIFace.FieldType.BooleanType, AttributeIFace.FieldType.StringType,
            // AttributeIFace.FieldType.MemoType
    };

    Session localSession = HibernateUtil.getCurrentSession();

    deleteAllRecordsFromTable(newDBConn, "collectionobjectattr", BasicSQLUtils.myDestinationServerType);
    deleteAllRecordsFromTable(newDBConn, "attributedef", BasicSQLUtils.myDestinationServerType);

    try {
        Statement stmt = oldDBConn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                ResultSet.CONCUR_READ_ONLY);
        stmt.setFetchSize(Integer.MIN_VALUE);

        // grab the field and their type from the old schema
        List<FieldMetaData> oldFieldMetaData = new ArrayList<FieldMetaData>();
        Map<String, FieldMetaData> oldFieldMetaDataMap = getFieldMetaDataFromSchemaHash(oldDBConn,
                "biologicalobjectattributes");

        // create maps to figure which columns where used
        List<String> columnsInUse = new ArrayList<String>();
        Map<String, AttributeDef> attrDefs = new Hashtable<String, AttributeDef>();

        List<Integer> counts = new ArrayList<Integer>();

        int totalCount = 0;

        for (FieldMetaData md : oldFieldMetaData) {
            // Skip these fields
            if (md.getName().indexOf("ID") == -1 && md.getName().indexOf("Timestamp") == -1
                    && md.getName().indexOf("LastEditedBy") == -1) {
                oldFieldMetaDataMap.put(md.getName(), md); // add to map for later

                // log.info(convertColumnName(md.getName())+" "+ md.getType());
                String sqlStr = "select count(" + md.getName() + ") from biologicalobjectattributes where "
                        + md.getName() + " is not null";
                ResultSet rs = stmt.executeQuery(sqlStr);
                if (rs.first() && rs.getInt(1) > 0) {
                    int rowCount = rs.getInt(1);
                    totalCount += rowCount;
                    counts.add(rowCount);

                    log.info(md.getName() + " has " + rowCount + " rows of values");

                    columnsInUse.add(md.getName());
                    AttributeDef attrDef = new AttributeDef();

                    String newName = convertColumnName(md.getName());
                    attrDef.setFieldName(newName);
                    log.debug("mapping[" + newName + "][" + md.getName() + "]");

                    // newNameToOldNameMap.put(newName, md.getName());

                    short dataType = -1;
                    if (typeMap != null) {
                        Short type = typeMap.get(md.getName());
                        if (type == null) {
                            dataType = type;
                        }
                    }

                    if (dataType == -1) {
                        dataType = getDataType(md.getName(), md.getType()).getType();
                    }

                    attrDef.setDataType(dataType);
                    attrDef.setDiscipline(discipline);
                    attrDef.setTableType(GenericDBConversion.TableType.CollectionObject.getType());
                    attrDef.setTimestampCreated(now);

                    attrDefs.put(md.getName(), attrDef);

                    try {
                        HibernateUtil.beginTransaction();
                        localSession.save(attrDef);
                        HibernateUtil.commitTransaction();

                    } catch (Exception e) {
                        log.error("******* " + e);
                        HibernateUtil.rollbackTransaction();
                        throw new RuntimeException(e);
                    }

                }
                rs.close();
            }
        } // for
        log.info("Total Number of Attrs: " + totalCount);

        // Now that we know which columns are being used we can start the conversion process

        log.info("biologicalobjectattributes columns in use: " + columnsInUse.size());
        if (columnsInUse.size() > 0) {
            int inx = 0;
            StringBuilder str = new StringBuilder("select BiologicalObjectAttributesID");
            for (String name : columnsInUse) {
                str.append(", ");
                str.append(name);
                inx++;
            }

            str.append(" from biologicalobjectattributes order by BiologicalObjectAttributesID");
            log.info("sql: " + str.toString());
            ResultSet rs = stmt.executeQuery(str.toString());

            int[] countVerify = new int[counts.size()];
            for (int i = 0; i < countVerify.length; i++) {
                countVerify[i] = 0;
            }
            boolean useHibernate = false;
            StringBuilder strBufInner = new StringBuilder();
            int recordCount = 0;
            while (rs.next()) {

                if (useHibernate) {
                    Criteria criteria = localSession.createCriteria(CollectionObject.class);
                    criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
                    criteria.add(Restrictions.eq("collectionObjectId", rs.getInt(1)));
                    List<?> list = criteria.list();
                    if (list.size() == 0) {
                        log.error("**** Can't find the CollectionObject " + rs.getInt(1));
                    } else {
                        CollectionObject colObj = (CollectionObject) list.get(0);

                        inx = 2; // skip the first column (the ID)
                        for (String name : columnsInUse) {
                            AttributeDef attrDef = attrDefs.get(name); // the needed
                                                                       // AttributeDef by name
                            FieldMetaData md = oldFieldMetaDataMap.get(name);

                            // Create the new Collection Object Attribute
                            CollectionObjectAttr colObjAttr = new CollectionObjectAttr();
                            colObjAttr.setCollectionObject(colObj);
                            colObjAttr.setDefinition(attrDef);
                            colObjAttr.setTimestampCreated(now);

                            // String oldName = newNameToOldNameMap.get(attrDef.getFieldName());
                            // log.debug("["+attrDef.getFieldName()+"]["+oldName+"]");

                            // log.debug(inx+" "+attrTypes[attrDef.getDataType()]+"
                            // "+md.getName()+" "+md.getType());
                            setData(rs, inx, attrTypes[attrDef.getDataType()], md, colObjAttr);

                            HibernateUtil.beginTransaction();
                            localSession.save(colObjAttr);
                            HibernateUtil.commitTransaction();

                            inx++;
                            if (recordCount % 2000 == 0) {
                                log.info("CollectionObjectAttr Records Processed: " + recordCount);
                            }
                            recordCount++;
                        } // for
                          // log.info("Done - CollectionObjectAttr Records Processed:
                          // "+recordCount);
                    }
                } else {
                    inx = 2; // skip the first column (the ID)
                    for (String name : columnsInUse) {
                        AttributeDef attrDef = attrDefs.get(name); // the needed AttributeDef
                                                                   // by name
                        FieldMetaData md = oldFieldMetaDataMap.get(name);

                        if (rs.getObject(inx) != null) {
                            Integer newRecId = (Integer) getMappedId(rs.getInt(1), "biologicalobjectattributes",
                                    "BiologicalObjectAttributesID");

                            Object data = getData(rs, inx, attrTypes[attrDef.getDataType()], md);
                            boolean isStr = data instanceof String;

                            countVerify[inx - 2]++;

                            strBufInner.setLength(0);
                            strBufInner.append("INSERT INTO collectionobjectattr VALUES (");
                            strBufInner.append("NULL");// Integer.toString(recordCount));
                            strBufInner.append(",");
                            strBufInner.append(getStrValue(isStr ? data : null));
                            strBufInner.append(",");
                            strBufInner.append(getStrValue(isStr ? null : data));
                            strBufInner.append(",");
                            strBufInner.append(getStrValue(now));
                            strBufInner.append(",");
                            strBufInner.append(getStrValue(now));
                            strBufInner.append(",");
                            strBufInner.append(newRecId.intValue());
                            strBufInner.append(",");
                            strBufInner.append(getStrValue(attrDef.getAttributeDefId()));
                            strBufInner.append(")");

                            try {
                                Statement updateStatement = newDBConn.createStatement();
                                // updateStatement.executeUpdate("SET FOREIGN_KEY_CHECKS = 0");
                                removeForeignKeyConstraints(newDBConn, BasicSQLUtils.myDestinationServerType);
                                if (false) {
                                    log.debug(strBufInner.toString());
                                }
                                updateStatement.executeUpdate(strBufInner.toString());
                                updateStatement.clearBatch();
                                updateStatement.close();
                                updateStatement = null;

                            } catch (SQLException e) {
                                log.error(strBufInner.toString());
                                log.error("Count: " + recordCount);
                                e.printStackTrace();
                                log.error(e);
                                throw new RuntimeException(e);
                            }

                            if (recordCount % 2000 == 0) {
                                log.info("CollectionObjectAttr Records Processed: " + recordCount);
                            }
                            recordCount++;
                        }
                        inx++;
                    } // for
                } // if
            } // while
            rs.close();
            stmt.close();

            log.info("Count Verification:");
            for (int i = 0; i < counts.size(); i++) {
                log.info(columnsInUse.get(i) + " [" + counts.get(i) + "][" + countVerify[i] + "] "
                        + (counts.get(i) - countVerify[i]));
            }
        }

    } catch (SQLException e) {
        e.printStackTrace();
        log.error(e);
        throw new RuntimeException(e);
    }
    return true;
}

From source file:edu.northwestern.bioinformatics.studycalendar.dao.SiteDao.java

License:BSD License

@SuppressWarnings({ "unchecked" })
private List<Site> getByIds(Collection<Integer> ids) {
    if (ids == null) {
        return getAll();
    } else if (ids.isEmpty()) {
        return Collections.emptyList();
    } else {//from  w  w w  . j  av a2 s.co m
        return getHibernateTemplate().findByCriteria(criteria().add(MoreRestrictions.in("id", ids))
                .setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY));
    }
}

From source file:edu.northwestern.bioinformatics.studycalendar.dao.StudyDao.java

License:BSD License

@SuppressWarnings({ "unchecked" })
private List<Study> getByIds(Collection<Integer> ids) {
    if (ids == null) {
        return getAll();
    } else if (ids.isEmpty()) {
        return Collections.emptyList();
    } else {/*w w w. j  a v  a 2 s .  c o  m*/
        return getHibernateTemplate().findByCriteria(criteria().add(MoreRestrictions.in("id", ids))
                .setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY));
    }
}