private void addDefaultCatalogFetch(Criteria criteria) { criteria.setFetchMode("catalogCategories", FetchMode.JOIN); criteria.createAlias( "catalogCategories.catalogCategoryAttributes", "catalogCategoryAttributes", JoinType.LEFT_OUTER_JOIN); criteria.setFetchMode("catalogCategoryAttributes", FetchMode.JOIN); }
public EmployeeBo retrieveEmployeeWithAttr(EmployeeBo inEmployeeBo) { if (null == inEmployeeBo || null == inEmployeeBo.getEmployeeId()) { return null; } Session session = getSession(); session.beginTransaction(); EmployeeBo employeeBo = null; Criteria empCriteria = session.createCriteria(EmployeeBo.class); empCriteria.add(Restrictions.eq("employeeId", inEmployeeBo.getEmployeeId())); empCriteria.createAlias("empAttributeSet", "empAttr"); empCriteria.createAlias("empAttributeSet.employeeAttributesBoID.attributeLookup", "attrLookup"); // empCriteria.createAlias("attrLookup.attrLookupGroup", "attrLookupGrp"); // attributeLookup ProjectionList projectionList = Projections.projectionList(); projectionList.add(Projections.property("employeeId")); projectionList.add(Projections.property("firstName")); projectionList.add(Projections.property("lastName")); // projectionList.add(Projections.property("attrLookupGrp.groupName")); projectionList.add(Projections.property("attrLookup.displayOrder")); projectionList.add(Projections.property("attrLookup.attrDesc")); projectionList.add(Projections.property("empAttr.attributeName")); projectionList.add(Projections.property("empAttr.attributeValue")); empCriteria.setProjection(projectionList); empCriteria.setFetchMode("empAttr", org.hibernate.FetchMode.EAGER); empCriteria.setFetchMode("attrLookup", org.hibernate.FetchMode.EAGER); // empCriteria.setFetchMode("attrLookupGrp", org.hibernate.FetchMode.EAGER); List<Object> empBoList = empCriteria.list(); if (null != empBoList) { System.out.println(" list size " + empBoList.size()); } for (Object data : empBoList) { Object[] projecObjArr = (Object[]) data; int count = 0; for (Object projecObj : projecObjArr) { System.out.print(" projecObjArr[" + count + "] " + projecObj); count++; } System.out.println(""); } return employeeBo; }
public Application getByIdWithCourses(Long id) { Criteria c = createCriteria(); c.add(Restrictions.idEq(id)); c.setFetchMode("courses", FetchMode.JOIN); return (Application) c.uniqueResult(); }
private final void fetchRelations( final Criteria criteria, final String relationName, final int relationDepth) { String relationPath = relationName; for (int i = 0; i < relationDepth; i++) { criteria.setFetchMode(relationPath, FetchMode.JOIN); relationPath += "." + relationName; } }
public Employee findOfficial(Integer id) { Criteria c = getCurrentSession().createCriteria(Employee.class, "employee"); c.setFetchMode("official", FetchMode.JOIN); c.createAlias("official", "official"); c.add(Restrictions.eq("employee.id", id)); return (Employee) c.uniqueResult(); }
public Instructor getByIdWithCourse(Long id) { Criteria c = createCriteria(); c.add(Restrictions.idEq(id)); c.setFetchMode("courses", FetchMode.JOIN); // first parameter gets field return (Instructor) c.uniqueResult(); }
@Override public List<Employee> findAimRelateWithEmployee(Integer id) { // TODO Auto-generated method stub Criteria c = getCurrentSession().createCriteria(Employee.class, "employee"); c.setFetchMode("aimempid", FetchMode.JOIN); c.createAlias("aimempid", "aimempid"); c.add(Restrictions.eq("aimempid.id", id)); return c.list(); }
public List<GameEntity> findByLeagueName(String leagueName) { Criteria criteria = getSession().createCriteria(GameEntity.class); criteria = criteria.createAlias("teamAway", "team"); criteria = criteria.setFetchMode("odds", FetchMode.SELECT); Criterion firstCri = Restrictions.eq("team.leagueName", leagueName); Criterion secondCri = Restrictions.eq("team.leagueNameEn", leagueName); Criterion criterion = Restrictions.or(firstCri, secondCri); return criteria.add(criterion).list(); }
private final Criteria createListSampleForTypeCriteria(final SampleTypePE sampleType) { final Criteria criteria = createListAllSamplesCriteria(); criteria.add(Restrictions.eq("sampleType", sampleType)); fetchRelations(criteria, "container", sampleType.getContainerHierarchyDepth()); fetchRelations(criteria, "generatedFrom", sampleType.getGeneratedFromHierarchyDepth()); criteria.setFetchMode("experimentInternal", FetchMode.JOIN); return criteria; }
public CatalogVirtual getVirtualCatalogByMarketAreaId(final Long marketAreaId) { Criteria criteria = createDefaultCriteria(CatalogVirtual.class); addDefaultCatalogFetch(criteria); criteria.setFetchMode("catalogMaster", FetchMode.JOIN); criteria.createAlias("marketArea", "ma", JoinType.LEFT_OUTER_JOIN); criteria.add(Restrictions.eq("ma.id", marketAreaId)); CatalogVirtual catalogVirtual = (CatalogVirtual) criteria.uniqueResult(); return catalogVirtual; }
@SuppressWarnings("unchecked") public List<T> getAll() { final Session session = this.sessionFactory.getCurrentSession(); final Criteria criteria = session.createCriteria(this.type); criteria.add(Restrictions.eq("deleted", false)); criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); criteria.setFetchMode("*", FetchMode.JOIN); return criteria.list(); }
private List<SamplePE> listSamplesByCriteria( final Criteria basicCriteria, boolean withExperimentAndProperties, Criterion... additionalCriterions) throws DataAccessException { for (Criterion criterion : additionalCriterions) { basicCriteria.add(criterion); } final int count = DAOUtils.getCount(basicCriteria); if (withExperimentAndProperties) { basicCriteria.setFetchMode("experimentInternal", FetchMode.JOIN); if (count <= DAOUtils.MAX_COUNT_FOR_PROPERTIES) { basicCriteria.setFetchMode("sampleProperties", FetchMode.JOIN); } else { operationLog.info(String.format("Found %d samples, disable properties loading.", count)); } } basicCriteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); return cast(basicCriteria.list()); }
@SuppressWarnings("unchecked") @Override public List<Schema> findByDataBase(long dataBaseId) { Criteria criteria = getSession().createCriteria(Schema.class); criteria.setFetchMode("dataBase", FetchMode.JOIN); criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY); criteria.add(Restrictions.eq("dataBase.id", dataBaseId)); return criteria.list(); }
@Override public void buildUnordered(Criteria criteria) { // Type check if (showEventTypesM.getObject().size() < numberOfEventTypes) criteria.add(Restrictions.in("type", showEventTypesM.getObject())); else log.debug("Not filtering by event type"); criteria.createAlias("user", "user"); // Site Check List<Site> siteList = showSitesM.getObject(); if (siteList.size() < numberOfSites || inAPeriod.getObject()) { criteria.createAlias("user.periods", "period", JoinType.LEFT_OUTER_JOIN); Disjunction siteRestriction = Restrictions.disjunction(); if (!inAPeriod.getObject()) siteRestriction.add(Restrictions.isEmpty("user.periods")); // Show users with no periods if (!siteList.isEmpty()) siteRestriction.add( Restrictions.in("period.site", siteList)); // Show users with matching periods if (inAPeriod.getObject() && siteList.isEmpty()) { siteRestriction.add(Restrictions.idEq(-1L)); // Halt query early; don't show anyone. criteria.setMaxResults(0); } criteria.add(siteRestriction); } else { log.debug("Not filtering by period/site"); } if (fromDateM.getObject() != null && toDateM.getObject() != null) { Date startDate = midnightStart(fromDateM.getObject()); Date endDate = midnightEnd(toDateM.getObject()); log.debug("Considering events between {} and {}", startDate, endDate); criteria.add(Restrictions.between("insertTime", startDate, endDate)); } // set permission check if (showPermissionUsers.getObject()) { criteria.add(Restrictions.eq("user.permission", true)); } // Also load ResponseData elements in the same query, to avoid thousands of subsequent // queries. criteria.setFetchMode("responseData", FetchMode.JOIN); // The join with periods results in multiple rows for multi-period users. // Unfortunately, this confuses the dataprovider, which still counts the duplicates // and therefore doesn't return a full page full of items each time. criteria.setResultTransformer( CriteriaSpecification .DISTINCT_ROOT_ENTITY); // Remove duplicate rows as a result of the INNER JOIN }
/** * Locates a <code>Criteria</code> for a <code>childEntityName</code>. If a <code>Criteria</code> * exists for the <code>childEntityName</code>, it is returned. If not, one is created and * referenced in the <code>childCriteriaMap</code> under the <code>childEntityName</code>. * * @param childEntityName * @param parentCriteria * @return criteria The Criteria for the childEntityName. * @throws org.hibernate.HibernateException */ private org.hibernate.Criteria locateCriteria( String childEntityName, org.hibernate.Criteria parentCriteria) throws org.hibernate.HibernateException { if (this.childCriteriaMap.containsKey(childEntityName)) { return (org.hibernate.Criteria) this.childCriteriaMap.get(childEntityName); } org.hibernate.Criteria childCriteria = parentCriteria.createCriteria(childEntityName); if (this.configuration.isForceEagerLoading()) { parentCriteria.setFetchMode(childEntityName, org.hibernate.FetchMode.JOIN); } this.childCriteriaMap.put(childEntityName, childCriteria); return childCriteria; }
public SamplePE tryToFindByPermID(String permID) throws DataAccessException { assert permID != null : "Unspecified permanent ID."; final Criteria criteria = getSession().createCriteria(ENTITY_CLASS); criteria.add(Restrictions.eq("permId", permID)); criteria.setFetchMode("sampleType.sampleTypePropertyTypesInternal", FetchMode.JOIN); final SamplePE sample = (SamplePE) criteria.uniqueResult(); if (operationLog.isDebugEnabled()) { operationLog.debug( String.format( "Following sample '%s' has been found for " + "permanent ID '%s'.", sample, permID)); } return sample; }
@Override public List<Cliente> listarPorNomes( String codigoPequisa, String nomePequisa, String placaPequisa, String ufPequisa, String situacao) { Criteria c = getSession().createCriteria(Cliente.class); Disjunction d = Restrictions.disjunction(); if (codigoPequisa != null && !codigoPequisa.equals("")) { d.add(Restrictions.ilike("codigo", codigoPequisa, MatchMode.ANYWHERE)); } if (nomePequisa != null && !nomePequisa.equals("")) { d.add(Restrictions.ilike("nome", nomePequisa, MatchMode.ANYWHERE)); d.add(Restrictions.ilike("razaoSocial", nomePequisa, MatchMode.ANYWHERE)); } if (ufPequisa != null && !ufPequisa.equals("") && !ufPequisa.equals("---")) { c.createAlias("enderecoPrimario", "endp"); c.createAlias("enderecoSecundario", "ends"); d.add(Restrictions.eq("endp.uf", ufPequisa)); d.add(Restrictions.eq("ends.uf", ufPequisa)); } if (placaPequisa != null && !placaPequisa.equals("")) { c.createAlias("veiculos", "vei"); d.add(Restrictions.ilike("vei.placa", placaPequisa, MatchMode.ANYWHERE)); } if (situacao != null && !situacao.equals("Todos")) { c.createAlias("contratos", "con"); for (SituacaoContrato s : SituacaoContrato.values()) { if (s.getValor().equals(situacao)) { d.add(Restrictions.eq("con.situacao", s)); } } } c.setFetchMode("contratos", FetchMode.SELECT); c.add(d); List<Cliente> clis = c.list(); for (Cliente cliente : clis) { Hibernate.initialize(cliente.getContratos()); } return clis; }
public CatalogVirtual getVirtualCatalogByMarketAreaId(final Long marketAreaId, Object... params) { Criteria criteria = createDefaultCriteria(CatalogVirtual.class); FetchPlan fetchPlan = handleSpecificFetchMode(criteria, params); criteria.setFetchMode("catalogMaster", FetchMode.JOIN); criteria.createAlias("marketArea", "marketArea", JoinType.LEFT_OUTER_JOIN); criteria.add(Restrictions.eq("marketArea.id", marketAreaId)); CatalogVirtual catalogVirtual = (CatalogVirtual) criteria.uniqueResult(); if (catalogVirtual != null) { catalogVirtual.setFetchPlan(fetchPlan); } return catalogVirtual; }
@SuppressWarnings("unchecked") public List<T> findByExample( T instance, Set<String> excludedProperties, Set<String> includedCollections, int fromRecord, int toRecord) { try { Example exampleInstance = create(instance); // Exclude the properties if (excludedProperties != null) { for (String excludedProperty : excludedProperties) { exampleInstance = exampleInstance.excludeProperty(excludedProperty); } } Criteria myCriteria = sessionFactory.getCurrentSession().createCriteria(clazz.getCanonicalName()); if (includedCollections != null) { // Include the collections for (String includedCollection : includedCollections) { myCriteria.setFetchMode(includedCollection, FetchMode.JOIN); } } // set the LIMIT if (fromRecord >= 0 && toRecord >= 0) { if (fromRecord < toRecord) { myCriteria.setFirstResult(fromRecord); myCriteria.setMaxResults(toRecord - fromRecord); } else { myCriteria.setFirstResult(toRecord); myCriteria.setMaxResults(fromRecord - toRecord); } } // Only get distinct Root entities myCriteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY); // get the results List<T> results = (List<T>) myCriteria.add(exampleInstance).list(); return results; } catch (RuntimeException re) { throw re; } }
public final SamplePE tryFindByCodeAndGroup(final String sampleCode, final GroupPE group) { assert sampleCode != null : "Unspecified sample code."; assert group != null : "Unspecified group."; final Criteria criteria = getSession().createCriteria(ENTITY_CLASS); addSampleCodeCriterion(criteria, sampleCode); criteria.add(Restrictions.eq("group", group)); criteria.setFetchMode("sampleType.sampleTypePropertyTypesInternal", FetchMode.JOIN); final SamplePE sample = (SamplePE) criteria.uniqueResult(); if (operationLog.isDebugEnabled()) { operationLog.debug( String.format( "Following sample '%s' has been found for code '%s' and group '%s'.", sample, sampleCode, group)); } return sample; }
public List<GameEntity> findByBallTypeAndGameStatus(String ballType, Long gameStatus) { Criteria criteria = getSession().createCriteria(GameEntity.class); criteria = criteria.setFetchMode("odds", FetchMode.SELECT); Criterion firstCri = Restrictions.eq("ballType", ballType); Criterion secondCri = Restrictions.eq("gameStatus", gameStatus); Criterion thirdCri = Restrictions.gt("gameTime", LocalDateTime.now()); Criterion extraCri = Restrictions.le("gameTime", LocalDateTime.now()); if (gameStatus != null) { if (gameStatus == 1L) criteria = criteria.add(firstCri).add(secondCri).add(thirdCri); else criteria = criteria.add(firstCri).add(secondCri); } else { gameStatus = 1L; secondCri = Restrictions.eq("gameStatus", gameStatus); criteria = criteria.add(firstCri).add(secondCri).add(extraCri); } return criteria.list(); }
public final SamplePE tryFindByCodeAndDatabaseInstance( final String sampleCode, final DatabaseInstancePE databaseInstance) { assert sampleCode != null : "Unspecified sample code."; assert databaseInstance != null : "Unspecified database instance."; final Criteria criteria = getSession().createCriteria(ENTITY_CLASS); addSampleCodeCriterion(criteria, sampleCode); criteria.add(Restrictions.eq("databaseInstance", databaseInstance)); criteria.setFetchMode("sampleType.sampleTypePropertyTypesInternal", FetchMode.JOIN); final SamplePE sample = (SamplePE) criteria.uniqueResult(); if (operationLog.isDebugEnabled()) { operationLog.debug( String.format( "Following sample '%s' has been found for " + "code '%s' and database instance '%s'.", sample, sampleCode, databaseInstance)); } return sample; }
void onActivate() { // flags = flagDAO.FindAllByContentType(ContentType.Question); // questions = new ArrayList<Question>(); sess = sessionManager.getSession(); sess.beginTransaction(); Criteria crit = sess.createCriteria(Flag.class); crit.add(Restrictions.eq("contentType", ContentType.Question)); crit.setFetchMode("question", FetchMode.JOIN); flags = crit.list(); System.out.println("first question of " + flags.size()); // sess.close(); // // flags = new ArrayList(); // for (int i = 0; i < temp.size(); i++) { // if(flags.contains(temp.get(i)) != true) { // flags.add(temp.get(i)); // } // } }
@SuppressWarnings("unchecked") public List<T> findByIds(Set<Long> ids, Set<String> includedCollections) { try { Criteria criteria = sessionFactory.getCurrentSession().createCriteria(clazz.getCanonicalName()); // Set the fetch mode for the collections to include if (includedCollections != null && includedCollections.size() != 0) { for (String includedCollection : includedCollections) { criteria.setFetchMode(includedCollection, FetchMode.JOIN); } } // Only get distinct Root entities criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY); List<T> results = (List<T>) criteria.add(Restrictions.in("id", ids)).list(); return results; } catch (RuntimeException re) { throw re; } }
@Override public <T extends GettableById> List<T> get( Class<T> bookKeywordEntityClass, String bookKeywordEntity, int offset, int limit, HashMap<String, FetchMode> fetchMode, HashMap<String, String> alias, Criterion... criterions) { validateTransaction(); Criteria criteria = getSession().createCriteria(bookKeywordEntityClass, bookKeywordEntity); criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); criteria.setFirstResult(offset); if (limit != 0) criteria.setMaxResults(limit); for (Criterion restriction : criterions) criteria.add(restriction); for (Map.Entry<String, FetchMode> stringObjectEntry : fetchMode.entrySet()) { criteria.setFetchMode(stringObjectEntry.getKey(), stringObjectEntry.getValue()); } for (Map.Entry<String, String> stringObjectEntry : alias.entrySet()) { criteria.createAlias(stringObjectEntry.getKey(), stringObjectEntry.getValue()); } return criteria.list(); }
/** * Populates criteria arguments for the given target class and arguments map * * @param datastore the GrailsApplication instance * @param targetClass The target class * @param c The criteria instance * @param argMap The arguments map */ @SuppressWarnings("rawtypes") public static void populateArgumentsForCriteria( AbstractHibernateDatastore datastore, Class<?> targetClass, Criteria c, Map argMap, ConversionService conversionService, boolean useDefaultMapping) { Integer maxParam = null; Integer offsetParam = null; if (argMap.containsKey(ARGUMENT_MAX)) { maxParam = conversionService.convert(argMap.get(ARGUMENT_MAX), Integer.class); } if (argMap.containsKey(ARGUMENT_OFFSET)) { offsetParam = conversionService.convert(argMap.get(ARGUMENT_OFFSET), Integer.class); } if (argMap.containsKey(ARGUMENT_FETCH_SIZE)) { c.setFetchSize(conversionService.convert(argMap.get(ARGUMENT_FETCH_SIZE), Integer.class)); } if (argMap.containsKey(ARGUMENT_TIMEOUT)) { c.setTimeout(conversionService.convert(argMap.get(ARGUMENT_TIMEOUT), Integer.class)); } if (argMap.containsKey(ARGUMENT_FLUSH_MODE)) { c.setFlushMode(convertFlushMode(argMap.get(ARGUMENT_FLUSH_MODE))); } if (argMap.containsKey(ARGUMENT_READ_ONLY)) { c.setReadOnly(ClassUtils.getBooleanFromMap(ARGUMENT_READ_ONLY, argMap)); } String orderParam = (String) argMap.get(ARGUMENT_ORDER); Object fetchObj = argMap.get(ARGUMENT_FETCH); if (fetchObj instanceof Map) { Map fetch = (Map) fetchObj; for (Object o : fetch.keySet()) { String associationName = (String) o; c.setFetchMode(associationName, getFetchMode(fetch.get(associationName))); } } final int max = maxParam == null ? -1 : maxParam; final int offset = offsetParam == null ? -1 : offsetParam; if (max > -1) { c.setMaxResults(max); } if (offset > -1) { c.setFirstResult(offset); } if (ClassUtils.getBooleanFromMap(ARGUMENT_LOCK, argMap)) { c.setLockMode(LockMode.PESSIMISTIC_WRITE); c.setCacheable(false); } else { if (argMap.containsKey(ARGUMENT_CACHE)) { c.setCacheable(ClassUtils.getBooleanFromMap(ARGUMENT_CACHE, argMap)); } else { cacheCriteriaByMapping(targetClass, c); } } final Object sortObj = argMap.get(ARGUMENT_SORT); if (sortObj != null) { boolean ignoreCase = true; Object caseArg = argMap.get(ARGUMENT_IGNORE_CASE); if (caseArg instanceof Boolean) { ignoreCase = (Boolean) caseArg; } if (sortObj instanceof Map) { Map sortMap = (Map) sortObj; for (Object sort : sortMap.keySet()) { final String order = ORDER_DESC.equalsIgnoreCase((String) sortMap.get(sort)) ? ORDER_DESC : ORDER_ASC; addOrderPossiblyNested(datastore, c, targetClass, (String) sort, order, ignoreCase); } } else { final String sort = (String) sortObj; final String order = ORDER_DESC.equalsIgnoreCase(orderParam) ? ORDER_DESC : ORDER_ASC; addOrderPossiblyNested(datastore, c, targetClass, sort, order, ignoreCase); } } else if (useDefaultMapping) { Mapping m = getDomainBinder().getMapping(targetClass); if (m != null) { Map sortMap = m.getSort().getNamesAndDirections(); for (Object sort : sortMap.keySet()) { final String order = ORDER_DESC.equalsIgnoreCase((String) sortMap.get(sort)) ? ORDER_DESC : ORDER_ASC; addOrderPossiblyNested(datastore, c, targetClass, (String) sort, order, true); } } } }
public List<Salon> getAllSalones(boolean includeEquipos) { Criteria crit = getSession().createCriteria(Salon.class); if (includeEquipos) crit = crit.setFetchMode("equipos", FetchMode.JOIN); return crit.list(); }
private void setFetchMode(Criteria criteria, boolean joinInfo) { if (joinInfo) { criteria.setFetchMode("info", FetchMode.JOIN); } }
/** * Set the fetch mode for a given association * * @param associationPath The association path * @param mode The fetch mode to apply * @return {@code this}, for method chaining */ public DetachedCriteria setFetchMode(String associationPath, FetchMode mode) { criteria.setFetchMode(associationPath, mode); return this; }