Example usage for org.hibernate Query setProperties

List of usage examples for org.hibernate Query setProperties

Introduction

In this page you can find the example usage for org.hibernate Query setProperties.

Prototype

Query<R> setProperties(Map bean);

Source Link

Document

Bind the values of the given Map for each named parameters of the query, matching key names with parameter names and mapping value types to Hibernate types using heuristics.

Usage

From source file:net.firejack.platform.core.store.BaseStore.java

License:Apache License

@Transactional(readOnly = true)
protected long countByQuery(final String queryStr, final Map queryParams) {
    return getHibernateTemplate().execute(new HibernateCallback<Long>() {
        public Long doInHibernate(Session session) throws HibernateException, SQLException {
            Query query = session.createQuery(queryStr);
            query.setProperties(queryParams);
            return (Long) query.uniqueResult();
        }/*  w w  w.ja va2 s .  c o  m*/
    });
}

From source file:net.sf.beanlib.hibernate3.DtoCentricHibernate3Template.java

License:Apache License

@Override
public @SuppressWarnings("unchecked") List findByValueBean(final String queryString, final Object valueBean)
        throws DataAccessException {
    return (List) execute(new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException {
            Query queryObject = session.createQuery(queryString);
            prepareQuery(queryObject);//from   w  w w  . j a va2 s  . c  o  m
            queryObject.setProperties(valueBean);
            return getHibernateDtoCopier().hibernate2dto(queryObject.list() /*, getSessionFactory() */);
        }
    });
}

From source file:net.sf.beanlib.hibernate3.DtoCentricHibernate3Template.java

License:Apache License

@Override
public @SuppressWarnings("unchecked") List findByNamedQueryAndValueBean(final String queryName,
        final Object valueBean) throws DataAccessException {
    return (List) execute(new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException {
            Query queryObject = session.getNamedQuery(queryName);
            prepareQuery(queryObject);/* w  ww .j  av a 2  s.c om*/
            queryObject.setProperties(valueBean);
            return getHibernateDtoCopier().hibernate2dto(queryObject.list() /*, getSessionFactory() */);
        }
    });
}

From source file:nl.strohalm.cyclos.utils.hibernate.HibernateQueryHandler.java

License:Open Source License

/**
 * Sets the query bind named parameters/*  w w  w  .j a va2s  . c o m*/
 */
public void setQueryParameters(final Query query, final Object parameters) {
    if (parameters != null) {
        if (parameters instanceof Map<?, ?>) {
            final Map<?, ?> map = (Map<?, ?>) parameters;
            final String[] paramNames = query.getNamedParameters();
            for (final String param : paramNames) {
                final Object value = map.get(param);
                if (value instanceof Collection<?>) {
                    final Collection<Object> values = new ArrayList<Object>(((Collection<?>) value).size());
                    for (final Object object : (Collection<?>) value) {
                        if (object instanceof EntityReference) {
                            values.add(fetchDao.fetch((Entity) object));
                        } else {
                            values.add(object);
                        }
                    }
                    query.setParameterList(param, values);
                } else if (value instanceof EntityReference) {
                    query.setParameter(param, fetchDao.fetch((Entity) value));
                } else {
                    query.setParameter(param, value);
                }
            }
        } else {
            query.setProperties(parameters);
        }
    }
}

From source file:no.abmu.common.persistence.hibernate3.AbstractQueryFinderSpecification.java

License:Open Source License

public Query createQuery(Session session) {

    String queryString;//from  w  ww .  java  2 s  .c  o  m

    if (StringUtil.isEmpty(getOrderBy())) {
        queryString = getQueryString();
    } else {
        queryString = getQueryString() + getOrderBy();
    }

    if (logger.isDebugEnabled()) {
        logger.debug("QueryString: [" + queryString + "]");
    }

    Query query = session.createQuery(queryString);

    if (usePropertiesBean()) {
        if (logger.isDebugEnabled()) {
            logger.debug("Using propertiesBean: " + getPropertiesBean());
        }
        query.setProperties(getPropertiesBean());
    }

    if (isPaged()) {
        if (logger.isDebugEnabled()) {
            logger.debug("Paging with firstElement " + getFirstElement() + ", and pageSize " + getPageSize());
        }
        query.setFirstResult(getFirstElement());
        query.setMaxResults(getPageSize());
    }

    if (isCaching()) {
        String cacheRegion = getCacheRegion();
        if (logger.isDebugEnabled()) {
            logger.debug("Caching is on in cacheRegion [" + cacheRegion + "]");
        }
        Query query2 = query.setCacheable(true).setCacheRegion(cacheRegion);
        return query2;
    }

    return query;
}

From source file:no.abmu.common.persistence.hibernate3.AbstractQueryFinderSpecification.java

License:Open Source License

public Query createQueryCount(Session session) {

    String countQueryString = getCountString();
    if (logger.isDebugEnabled()) {
        logger.debug("QueryCountString: " + countQueryString);
    }/*from ww  w .ja  v  a2  s  .  com*/

    Query query = session.createQuery(countQueryString);
    if (usePropertiesBean()) {
        query.setProperties(getPropertiesBean());
    }

    return query;
}

From source file:org.archiviststoolkit.mydomain.DomainAccessObjectImpl.java

License:Open Source License

/**
 * Return a collection which conforms to the named query.
 * TODO: check the bean interface to queries
 *
 * @param queryName      the name of the query
 * @param propertyObject the bean which is used to pass properties to the query
 * @return the collection generated by the query
 * @throws LookupException fails if we cannot execute the named query
 *///from   w  ww .  jav a  2s.c o  m

public final Collection findByNamedQuery(final String queryName, final Object propertyObject)
        throws LookupException {
    List filteredList;

    Session session = SessionFactory.getInstance().openSession(getPersistentClass());
    try {
        Query query = session.getNamedQuery(queryName);

        query.setProperties(propertyObject);

        filteredList = query.list();
        session.flush();
        session.connection().commit();

    } catch (HibernateException hibernateException) {
        throw new LookupException("failed to findbynamedquery 1", hibernateException);
    } catch (SQLException sqlException) {
        throw new LookupException("failed to findbynamedquery 2", sqlException);
    }

    SessionFactory.getInstance().closeSession(session);

    return (filteredList);
}

From source file:org.jasig.ssp.util.sort.SortingAndPaging.java

License:Apache License

public Pair<Long, Query> applySortingAndPagingToPagedQuery(Object session, final String countColumn,
        final String hqlSelectClause, final StringBuilder hqlWithoutSelect, final boolean filterByStatus,
        String objectToAddStatusFilter, Boolean isInitialRestriction, Map<String, Object> bindParams) {

    if (filterByStatus && StringUtils.isNotBlank(objectToAddStatusFilter)) {
        addStatusFilterToQuery(hqlWithoutSelect, objectToAddStatusFilter, isInitialRestriction);
        bindParams.put("objectStatus", getStatus());
    }/*from w ww  .  j  a  v a 2  s  . c  om*/

    // When using HQL, subqueries can only occur in the select and the where, not in the from.
    // So we have the client explicitly tell us where the select clause ends and the from+where
    // clause begins so we can unambiguously execute the latter twice, once with our count()
    // function and once for the "real" results. (Parsing to find where the from clause starts is
    // fraught. E.g. see https://issues.jasig.org/browse/SSP-2192 and related tickets.)
    final StringBuilder rowCntHql = new StringBuilder("select ");
    if (StringUtils.isBlank(countColumn)) {
        rowCntHql.append("count(*) ");
    } else {
        rowCntHql.append("count(distinct ").append(countColumn).append(") ");
    }
    rowCntHql.append(hqlWithoutSelect);

    Query fullQuery = null;
    Query rowCntQuery = null;
    final StringBuilder fullHql = new StringBuilder(hqlSelectClause)
            .append(addSortingToQuery(hqlWithoutSelect));
    if (session instanceof Session) {
        Session thisSession = (Session) session;
        fullQuery = addPagingToQuery(thisSession.createQuery(fullHql.toString())).setProperties(bindParams);
        fullQuery = postProcessBindParams(fullQuery, bindParams);
        rowCntQuery = thisSession.createQuery(rowCntHql.toString());
    } else if (session instanceof StatelessSession) {
        StatelessSession thisStatelessSession = (StatelessSession) session;
        fullQuery = addPagingToQuery(thisStatelessSession.createQuery(fullHql.toString()))
                .setProperties(bindParams);
        fullQuery = postProcessBindParams(fullQuery, bindParams);
        rowCntQuery = thisStatelessSession.createQuery(rowCntHql.toString());
    } else {
        throw new IllegalArgumentException(
                "session paramter for org.jasig.ssp.util.sort.SortingAndPaging.applySortingAndPagingToPagedQuery(Object, StringBuilder, boolean, String, Boolean, Map<String, Object>) must "
                        + "must be of type Session or StatelessSession");
    }

    rowCntQuery.setProperties(bindParams);
    rowCntQuery = postProcessBindParams(rowCntQuery, bindParams);
    final Long totalRows = (Long) rowCntQuery.list().get(0);

    // Sorting not added until here b/c if it's present in the count() query
    // above, the db will usually complain about that field not being
    // present in a group by/aggr function
    return new Pair<Long, Query>(totalRows, fullQuery);
}

From source file:org.jdal.dao.hibernate.HibernateDao.java

License:Apache License

/**
 * Get Hibernate named Query and configure with filter from page. 
 * Set the result count on page also. /*from   w ww .  j a  v a2  s  .  c  o m*/
 * @param page page 
 * @return Hibernate named Query.
 */
private Query getQuery(Page<?> page) {
    Object filter = page.getFilter();

    try {
        if (filter instanceof Filter) {
            Filter f = (Filter) filter;
            Query query = getSession().getNamedQuery(f.getFilterName());
            Query countQuery = getSession().createQuery(query.getQueryString().replaceFirst("select", "count"));
            query.setProperties(f.getParameterMap());
            query.setMaxResults(page.getPageSize());
            query.setFirstResult(page.getStartIndex());
            page.setCount((Integer) countQuery.uniqueResult());

            return query;
        }
    } catch (HibernateException e) {
    }
    return null;
}

From source file:org.mifos.accounts.persistence.LegacyAccountDao.java

License:Open Source License

private List executeNamedQueryAtInit(String queryName, Map queryParameters) throws PersistenceException {
    Session session = null;/*from www.  j  av a 2s.  c  om*/
    try {
        session = StaticHibernateUtil.getSessionTL();
        Query query = session.getNamedQuery(queryName);
        query.setProperties(queryParameters);
        return query.list();
    } catch (Exception e) {
        throw new PersistenceException(e);
    }
}