Example usage for org.hibernate Query setEntity

List of usage examples for org.hibernate Query setEntity

Introduction

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

Prototype

@Deprecated
@SuppressWarnings("unchecked")
Query<R> setEntity(String name, Object val);

Source Link

Document

Bind an instance of a mapped persistent class to a named query parameter.

Usage

From source file:org.brekka.pegasus.core.dao.hibernate.RobotHibernateDAO.java

License:Apache License

@Override
public int retrieveListingRowCount(final Actor owner) {
    String sql = "select count(r) from Robot r" + " where r.status in (:active, :disabled)";
    if (owner != null) {
        sql += "   and r.owner=:owner";
    }//from   w w w.j a va  2  s  . c  o  m
    Query query = getCurrentSession().createQuery(sql);
    if (owner != null) {
        query.setEntity("owner", owner);
    }
    query.setParameter("active", ActorStatus.ACTIVE);
    query.setParameter("disabled", ActorStatus.DISABLED);
    return ((Number) query.uniqueResult()).intValue();
}

From source file:org.eclipse.emf.cdo.server.internal.hibernate.HibernateQueryHandler.java

License:Open Source License

/**
 * Executes hql queries. Gets the session from the {@link HibernateStoreAccessor} creates a hibernate query and sets
 * the parameters taken from the {@link CDOQueryInfo#getParameters()}. Takes into account the
 * {@link CDOQueryInfo#getMaxResults()} and the {@link IHibernateStore#FIRST_RESULT} values for paging.
 *
 * @param info//from w ww  .  j av  a  2 s. c o  m
 *          the object containing the query and parameters
 * @param context
 *          the query results are placed in the context
 * @see IQueryHandler#executeQuery(CDOQueryInfo, IQueryContext)
 */
public void executeQuery(CDOQueryInfo info, IQueryContext context) {
    // get a transaction, the hibernateStoreAccessor is placed in a threadlocal
    // so all db access uses the same session.
    final Session session = hibernateStoreAccessor.getHibernateSession();
    try {
        // create the query
        final Query query = session.createQuery(info.getQueryString());
        query.setReadOnly(true);

        // get the parameters with some parameter conversion
        int firstResult = -1;
        boolean cacheResults = true;
        for (String key : info.getParameters().keySet()) {
            if (key.compareToIgnoreCase(IHibernateStore.CACHE_RESULTS) == 0) {
                try {
                    cacheResults = (Boolean) info.getParameters().get(key);
                } catch (ClassCastException e) {
                    throw new IllegalArgumentException("Parameter " + IHibernateStore.CACHE_RESULTS //$NON-NLS-1$
                            + " must be a boolean. errorMessage " + e.getMessage());
                }
            } else if (key.compareToIgnoreCase(IHibernateStore.FIRST_RESULT) == 0) {
                final Object o = info.getParameters().get(key);
                if (o != null) {
                    try {
                        firstResult = (Integer) o;
                    } catch (ClassCastException e) {
                        throw new IllegalArgumentException(
                                "Parameter firstResult must be an integer but it is a " + o //$NON-NLS-1$
                                        + " class " + o.getClass().getName()); //$NON-NLS-1$
                    }
                }
            } else {
                // in case the parameter is a CDOID get the object from the db
                final Object param = info.getParameters().get(key);
                if (param instanceof CDOID && HibernateUtil.getInstance().isStoreCreatedID((CDOID) param)) {
                    final CDOID id = (CDOID) param;
                    final String entityName = HibernateUtil.getInstance().getEntityName(id);
                    final Serializable idValue = HibernateUtil.getInstance().getIdValue(id);
                    final CDORevision revision = (CDORevision) session.get(entityName, idValue);
                    query.setEntity(key, revision);
                    if (cacheResults) {
                        addToRevisionCache(revision);
                    }
                } else {
                    query.setParameter(key, param);
                }
            }
        }

        // set the first result
        if (firstResult > -1) {
            query.setFirstResult(firstResult);
        }

        // the max result
        if (info.getMaxResults() != CDOQueryInfo.UNLIMITED_RESULTS) {
            query.setMaxResults(info.getMaxResults());
        }

        final ScrollableResults scroller = query.scroll(ScrollMode.FORWARD_ONLY);

        // and go for the query
        // future extension: support iterate, scroll through a parameter
        int i = 0;
        try {
            while (scroller.next()) {
                Object[] os = scroller.get();
                Object o;
                if (os.length == 1) {
                    o = handleAuditEntries(os[0]);
                } else {
                    o = handleAuditEntries(os);
                }

                final boolean addOneMore = context.addResult(o);
                if (cacheResults && o instanceof CDORevision) {
                    addToRevisionCache((CDORevision) o);
                }
                if (o instanceof InternalCDORevision) {
                    ((InternalCDORevision) o).freeze();
                }

                // clear the session every 1000 results or so
                if (i++ % 1000 == 0) {
                    session.clear();
                }

                if (!addOneMore) {
                    return;
                }
            }
        } finally {
            scroller.close();
        }
    } finally {
        session.close();
    }
}

From source file:org.eclipse.emf.cdo.server.internal.hibernate.HibernateStoreAccessor.java

License:Open Source License

public void queryXRefs(QueryXRefsContext context) {
    final Session session = getHibernateSession();
    for (CDOID targetCdoId : context.getTargetObjects().keySet()) {
        final CDORevision revision = HibernateUtil.getInstance().getCDORevision(targetCdoId);
        final EClass targetEClass = context.getTargetObjects().get(targetCdoId);

        if (!getStore().isMapped(targetEClass)) {
            continue;
        }/*w w w.j av  a2s  .c om*/

        final String targetEntityName = getStore().getEntityName(targetEClass);
        final Map<EClass, List<EReference>> sourceCandidates = context.getSourceCandidates();
        for (EClass sourceEClass : sourceCandidates.keySet()) {

            if (!getStore().isMapped(sourceEClass)) {
                continue;
            }

            final String sourceEntityName = getStore().getEntityName(sourceEClass);
            for (EReference eref : sourceCandidates.get(sourceEClass)) {
                // handle transient ereferences
                if (!isEReferenceMapped(session, sourceEntityName, eref)) {
                    continue;
                }

                final String hql;
                if (eref.isMany()) {
                    hql = "select ref from " + sourceEntityName + " as ref, " + targetEntityName
                            + " as refTo where refTo = :to and refTo in elements(ref." + eref.getName() + ")";
                } else {
                    hql = "select ref from " + sourceEntityName + " as ref where :to = ref." + eref.getName();
                }

                final Query qry = session.createQuery(hql);
                qry.setEntity("to", revision);
                ScrollableResults result = qry.scroll(ScrollMode.FORWARD_ONLY);
                while (result.next()) {
                    final InternalCDORevision sourceRevision = (InternalCDORevision) result.get()[0];

                    sourceRevision.freeze();

                    int sourceIndex = 0;
                    if (eref.isMany()) {
                        // note this takes performance for sure as the list is read,
                        // consider not supporting sourceIndex, or doing it differently
                        final WrappedHibernateList cdoList = (WrappedHibernateList) sourceRevision
                                .getList(eref);
                        sourceIndex = cdoList.getDelegate().indexOf(revision);
                    }

                    boolean more = context.addXRef(targetCdoId, sourceRevision.getID(), eref, sourceIndex);
                    if (!more) {
                        return;
                    }
                }
            }
        }
    }
}

From source file:org.eclipse.emf.teneo.hibernate.HbSessionWrapper.java

License:Open Source License

/** Query */
public List<?> executeQuery(String qry, String entityParameter, Object entity) {
    final Query query = getSessionInternal().createQuery(qry);
    query.setEntity(entityParameter, entity);
    return query.list();
}

From source file:org.egov.commons.dao.InstallmentHibDao.java

License:Open Source License

@Override
public List<Installment> getInsatllmentByModule(final Module module) {
    final Query qry = getCurrentSession()
            .createQuery("from Installment I where I.module=:module order by installmentYear desc");
    qry.setEntity("module", module);

    return qry.list();
}

From source file:org.egov.commons.dao.InstallmentHibDao.java

License:Open Source License

@Override
public List getInsatllmentByModule(final Module module, final Date year) {
    final Query qry = getCurrentSession()
            .createQuery("from Installment I where I.module=:module and I.installmentYear=:year");
    qry.setEntity("module", module);
    qry.setDate("year", year);

    return qry.list();
}

From source file:org.egov.commons.dao.InstallmentHibDao.java

License:Open Source License

@Override
public Installment getInsatllmentByModule(final Module module, final Date year,
        final Integer installmentNumber) {
    final Query qry = getCurrentSession().createQuery(
            "from Installment I where I.module=:module and I.installmentYear=:year and I.installmentNumber =:instNum");
    qry.setEntity("module", module);
    qry.setDate("year", year);
    qry.setInteger("instNum", installmentNumber);

    return (Installment) qry.uniqueResult();
}

From source file:org.egov.commons.dao.InstallmentHibDao.java

License:Open Source License

@Override
public Installment getInsatllmentByModuleForGivenDate(final Module module, final Date installmentDate) {
    final Query qry = getCurrentSession().createQuery(
            "from Installment I where I.module=:module and (I.fromDate <= :fromYear and I.toDate >=:toYear)");
    qry.setEntity("module", module);
    qry.setDate("fromYear", installmentDate);
    qry.setDate("toYear", installmentDate);

    return (Installment) qry.uniqueResult();

}

From source file:org.egov.commons.dao.InstallmentHibDao.java

License:Open Source License

@Override
public List<Installment> getEffectiveInstallmentsforModuleandDate(final Date dateToCompare,
        final int noOfMonths, final Module mod) {
    final Query qry = getCurrentSession().createQuery(
            "from org.egov.commons.Installment inst where  inst.toDate >= :dateToCompare and inst.toDate < :dateToComparemax   and inst.module=:module");
    qry.setDate("dateToCompare", dateToCompare);
    qry.setEntity("module", mod);
    final Date dateToComparemax = DateUtils.add(dateToCompare, Calendar.MONTH, noOfMonths);
    qry.setDate("dateToComparemax", dateToComparemax);

    return qry.list();
}

From source file:org.egov.commons.dao.InstallmentHibDao.java

License:Open Source License

@Override
public Installment getInsatllmentByModuleForGivenDateAndInstallmentType(final Module module,
        final Date installmentDate, final String installmentType) {
    final Query qry = getCurrentSession().createQuery(
            "from Installment I where I.module=:module and (I.fromDate <= :fromYear and I.toDate >=:toYear) and I.installmentType = :installmentType");
    qry.setEntity("module", module);
    qry.setDate("fromYear", installmentDate);
    qry.setDate("toYear", installmentDate);
    qry.setString("installmentType", installmentType);
    return (Installment) qry.uniqueResult();
}