Search in sources :

Example 11 with Criteria

use of org.hibernate.Criteria in project head by mifos.

the class PersonnelDaoHibernate method search.

@SuppressWarnings("unchecked")
@Override
public SystemUserSearchResultsDto search(UserSearchDto searchDto, MifosUser user) {
    Short userId = Integer.valueOf(user.getUserId()).shortValue();
    PersonnelBO loggedInUser = findPersonnelById(userId);
    final PersonnelLevel level = loggedInUser.getLevelEnum();
    final String searchAllSubOfficesInclusiveOfLoggedInUserOffice = loggedInUser.getOfficeSearchId() + "%";
    final String searchString = org.mifos.framework.util.helpers.SearchUtils.normalizeSearchString(searchDto.getSearchTerm());
    final String username = searchString + "%";
    String firstName = "";
    String secondPartOfName = "";
    HashMap<String, Object> queryParameters = new HashMap<String, Object>();
    queryParameters.put("SEARCH_ALL", searchAllSubOfficesInclusiveOfLoggedInUserOffice);
    queryParameters.put("USERID", userId);
    queryParameters.put("LOID", PersonnelLevel.LOAN_OFFICER.getValue());
    queryParameters.put("USERLEVEL_ID", level.getValue());
    queryParameters.put("USER_NAME", username);
    if (searchString.contains(" ")) {
        firstName = searchString.substring(0, searchString.indexOf(" "));
        secondPartOfName = searchString.substring(searchString.indexOf(" ") + 1, searchString.length());
        queryParameters.put("USER_NAME1", firstName);
        queryParameters.put("USER_NAME2", secondPartOfName);
    } else {
        firstName = searchString;
        secondPartOfName = "";
        queryParameters.put("USER_NAME1", searchString);
        queryParameters.put("USER_NAME2", "");
    }
    Long searchResultsCount = (Long) this.genericDao.executeUniqueResultNamedQuery(NamedQueryConstants.PERSONNEL_SEARCH_COUNT, queryParameters);
    Session session = StaticHibernateUtil.getSessionTL();
    Criteria criteriaQuery = session.createCriteria(PersonnelBO.class);
    criteriaQuery.createAlias("office", "o");
    criteriaQuery.createAlias("personnelDetails", "d");
    if (PersonnelLevel.LOAN_OFFICER.getValue().equals(Short.valueOf("2"))) {
        criteriaQuery.add(Restrictions.eq("personnelId", userId));
    }
    criteriaQuery.add(Restrictions.like("o.searchId", searchAllSubOfficesInclusiveOfLoggedInUserOffice));
    LogicalExpression firstOrLastNameMatchUsername = Restrictions.or(Restrictions.like("d.name.firstName", username), Restrictions.like("d.name.lastName", username));
    LogicalExpression firstNameAndLastNameMatchGivenParts = Restrictions.and(Restrictions.like("d.name.firstName", firstName), Restrictions.like("d.name.lastName", secondPartOfName));
    criteriaQuery.add(Restrictions.or(firstOrLastNameMatchUsername, firstNameAndLastNameMatchGivenParts));
    criteriaQuery.addOrder(Order.asc("o.officeName"));
    criteriaQuery.addOrder(Order.asc("d.name.lastName"));
    criteriaQuery.setFetchMode("office", FetchMode.JOIN);
    criteriaQuery.setFetchMode("level", FetchMode.JOIN);
    criteriaQuery.setFetchMode("personnelDetails", FetchMode.JOIN);
    int firstResult = (searchDto.getPage() * searchDto.getPageSize()) - searchDto.getPageSize();
    criteriaQuery.setFirstResult(firstResult);
    criteriaQuery.setMaxResults(searchDto.getPageSize());
    List<PersonnelBO> pagedResults = criteriaQuery.list();
    List<UserDetailDto> pagedUserDetails = new ArrayList<UserDetailDto>();
    for (PersonnelBO personnelBO : pagedResults) {
        pagedUserDetails.add(personnelBO.toDto());
    }
    SystemUserSearchResultsDto resultsDto = new SystemUserSearchResultsDto(searchResultsCount.intValue(), firstResult, searchDto.getPage(), searchDto.getPageSize(), pagedUserDetails);
    return resultsDto;
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Criteria(org.hibernate.Criteria) LogicalExpression(org.hibernate.criterion.LogicalExpression) PersonnelBO(org.mifos.customers.personnel.business.PersonnelBO) UserDetailDto(org.mifos.dto.domain.UserDetailDto) PersonnelLevel(org.mifos.customers.personnel.util.helpers.PersonnelLevel) SystemUserSearchResultsDto(org.mifos.dto.screen.SystemUserSearchResultsDto) Session(org.hibernate.Session)

Example 12 with Criteria

use of org.hibernate.Criteria in project gocd by gocd.

the class EnvironmentVariableSqlMapDao method load.

public EnvironmentVariablesConfig load(final Long entityId, final EnvironmentVariableType type) {
    List<EnvironmentVariableConfig> result = (List<EnvironmentVariableConfig>) transactionTemplate.execute(new TransactionCallback() {

        @Override
        public Object doInTransaction(TransactionStatus transactionStatus) {
            Criteria criteria = sessionFactory.getCurrentSession().createCriteria(EnvironmentVariableConfig.class).add(Restrictions.eq("entityId", entityId)).add(Restrictions.eq("entityType", type.toString())).addOrder(Order.asc("id"));
            criteria.setCacheable(true);
            return criteria.list();
        }
    });
    for (EnvironmentVariableConfig var : result) {
        var.ensureEncrypted();
    }
    return new EnvironmentVariablesConfig(result);
}
Also used : EnvironmentVariableConfig(com.thoughtworks.go.config.EnvironmentVariableConfig) TransactionCallback(org.springframework.transaction.support.TransactionCallback) EnvironmentVariablesConfig(com.thoughtworks.go.config.EnvironmentVariablesConfig) TransactionStatus(org.springframework.transaction.TransactionStatus) List(java.util.List) Criteria(org.hibernate.Criteria)

Example 13 with Criteria

use of org.hibernate.Criteria in project hibernate-orm by hibernate.

the class StatementCacheTest method testStatementCaching.

@Test
@TestForIssue(jiraKey = "HHH-7193")
public void testStatementCaching() {
    Session session = openSession();
    session.beginTransaction();
    //save 2 new entities, one valid, one invalid (neither should be persisted)
    IrrelevantEntity irrelevantEntity = new IrrelevantEntity();
    irrelevantEntity.setName("valid 1");
    session.save(irrelevantEntity);
    //name is required
    irrelevantEntity = new IrrelevantEntity();
    session.save(irrelevantEntity);
    try {
        session.flush();
        Assert.fail("Validation exception did not occur");
    } catch (Exception e) {
        //this is expected roll the transaction back
        session.getTransaction().rollback();
    }
    session.close();
    session = openSession();
    session.beginTransaction();
    //save a new entity and commit it
    irrelevantEntity = new IrrelevantEntity();
    irrelevantEntity.setName("valid 2");
    session.save(irrelevantEntity);
    session.flush();
    session.getTransaction().commit();
    session.close();
    //only one entity should have been inserted to the database (if the statement in the cache wasn't cleared then it would have inserted both entities)
    session = openSession();
    session.beginTransaction();
    Criteria criteria = session.createCriteria(IrrelevantEntity.class);
    List results = criteria.list();
    session.getTransaction().commit();
    session.close();
    Assert.assertEquals(1, results.size());
}
Also used : List(java.util.List) Criteria(org.hibernate.Criteria) Session(org.hibernate.Session) Test(org.junit.Test) TestForIssue(org.hibernate.testing.TestForIssue)

Example 14 with Criteria

use of org.hibernate.Criteria in project hibernate-orm by hibernate.

the class CriteriaJoinWalker method generateTableAlias.

@Override
protected String generateTableAlias(int n, PropertyPath path, Joinable joinable) {
    // TODO: deal with side-effects (changes to includeInResultRowList, userAliasList, resultTypeList)!!!
    // for collection-of-entity, we are called twice for given "path"
    // once for the collection Joinable, once for the entity Joinable.
    // the second call will/must "consume" the alias + perform side effects according to consumesEntityAlias()
    // for collection-of-other, however, there is only one call 
    // it must "consume" the alias + perform side effects, despite what consumeEntityAlias() return says
    // 
    // note: the logic for adding to the userAliasList is still strictly based on consumesEntityAlias return value
    boolean checkForSqlAlias = joinable.consumesEntityAlias();
    if (!checkForSqlAlias && joinable.isCollection()) {
        // is it a collection-of-other (component or value) ?
        CollectionPersister collectionPersister = (CollectionPersister) joinable;
        Type elementType = collectionPersister.getElementType();
        if (elementType.isComponentType() || !elementType.isEntityType()) {
            checkForSqlAlias = true;
        }
    }
    String sqlAlias = null;
    if (checkForSqlAlias) {
        final Criteria subcriteria = translator.getCriteria(path.getFullPath());
        sqlAlias = subcriteria == null ? null : translator.getSQLAlias(subcriteria);
        if (joinable.consumesEntityAlias() && !translator.hasProjection()) {
            includeInResultRowList.add(subcriteria != null && subcriteria.getAlias() != null);
            if (sqlAlias != null) {
                if (subcriteria.getAlias() != null) {
                    userAliasList.add(subcriteria.getAlias());
                    resultTypeList.add(translator.getResultType(subcriteria));
                }
            }
        }
    }
    if (sqlAlias == null) {
        sqlAlias = super.generateTableAlias(n + translator.getSQLAliasCount(), path, joinable);
    }
    return sqlAlias;
}
Also used : JoinType(org.hibernate.sql.JoinType) AssociationType(org.hibernate.type.AssociationType) Type(org.hibernate.type.Type) CollectionPersister(org.hibernate.persister.collection.CollectionPersister) Criteria(org.hibernate.Criteria)

Example 15 with Criteria

use of org.hibernate.Criteria in project hibernate-orm by hibernate.

the class CriteriaQueryTranslator method createCriteriaEntityNameMap.

private void createCriteriaEntityNameMap() {
    // initialize the rootProvider first
    final CriteriaInfoProvider rootProvider = new EntityCriteriaInfoProvider((Queryable) sessionFactory.getEntityPersister(rootEntityName));
    criteriaInfoMap.put(rootCriteria, rootProvider);
    nameCriteriaInfoMap.put(rootProvider.getName(), rootProvider);
    for (final String key : associationPathCriteriaMap.keySet()) {
        final Criteria value = associationPathCriteriaMap.get(key);
        final CriteriaInfoProvider info = getPathInfo(key);
        criteriaInfoMap.put(value, info);
        nameCriteriaInfoMap.put(info.getName(), info);
    }
}
Also used : Criteria(org.hibernate.Criteria)

Aggregations

Criteria (org.hibernate.Criteria)174 Session (org.hibernate.Session)92 Test (org.junit.Test)69 Transaction (org.hibernate.Transaction)39 List (java.util.List)35 DetachedCriteria (org.hibernate.criterion.DetachedCriteria)27 ArrayList (java.util.ArrayList)15 TestForIssue (org.hibernate.testing.TestForIssue)12 Iterator (java.util.Iterator)9 Period (org.hisp.dhis.period.Period)8 Map (java.util.Map)6 State (org.hibernate.test.cache.infinispan.functional.entities.State)5 OnmsCriteria (org.opennms.netmgt.model.OnmsCriteria)4 HibernateCallback (org.springframework.orm.hibernate3.HibernateCallback)4 HashSet (java.util.HashSet)3 Criterion (org.hibernate.criterion.Criterion)3 Example (org.hibernate.criterion.Example)3 Statistics (org.hibernate.stat.Statistics)3 Pager (org.hisp.dhis.common.Pager)3 PolyString (com.evolveum.midpoint.prism.polystring.PolyString)2