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.jbpm.db.TaskMgmtSession.java

License:Open Source License

/**
 * get active taskinstances for a given token.
 *//* w  ww. j av a2 s .c  om*/
public List findTaskInstancesByProcessInstance(ProcessInstance processInstance) {
    List result = null;
    try {
        Query query = session.getNamedQuery("TaskMgmtSession.findTaskInstancesByProcessInstance");
        query.setEntity("processInstance", processInstance);
        result = query.list();
    } catch (Exception e) {
        log.error(e);
        jbpmSession.handleException();
        throw new JbpmException("couldn't get task instances by process instance '" + processInstance + "'", e);
    }
    return result;
}

From source file:org.jbpm.pvm.internal.hibernate.DbSessionImpl.java

License:Open Source License

public void cascadeExecutionSuspend(ExecutionImpl execution) {
    // cascade suspend to jobs
    Query query = session.createQuery("select job " + "from " + JobImpl.class.getName() + " as job "
            + "where job.execution = :execution " + "  and job.state != '" + JobImpl.STATE_SUSPENDED + "' ");
    query.setEntity("execution", execution);
    query.setLockMode("job", LockMode.NONE);

    List<JobImpl> jobs = query.list();
    for (JobImpl job : jobs) {
        job.suspend();/* w w  w  . j  a v a  2s .c o  m*/
    }

    // cascade suspend to tasks
    query = session.createQuery("select task " + "from " + TaskImpl.class.getName() + " as task "
            + "where task.execution = :execution " + "  and task.state != '" + Task.STATE_SUSPENDED + "' ");
    query.setEntity("execution", execution);
    query.setLockMode("task", LockMode.NONE);

    List<TaskImpl> tasks = query.list();
    for (TaskImpl task : tasks) {
        task.suspend();
    }
}

From source file:org.jbpm.pvm.internal.hibernate.DbSessionImpl.java

License:Open Source License

public void cascadeExecutionResume(ExecutionImpl execution) {
    // cascade suspend to jobs
    Query query = session.createQuery("select job " + "from " + JobImpl.class.getName() + " as job "
            + "where job.execution = :execution " + "  and job.state = '" + Task.STATE_SUSPENDED + "' ");
    query.setEntity("execution", execution);
    query.setLockMode("job", LockMode.NONE);

    List<JobImpl> jobs = query.list();
    for (JobImpl job : jobs) {
        job.resume();// w  w  w.j  a  v  a  2 s  . c  om
    }

    // cascade suspend to tasks
    query = session.createQuery("select task " + "from " + TaskImpl.class.getName() + " as task "
            + "where task.execution = :execution " + "  and task.state = '" + Task.STATE_SUSPENDED + "' ");
    query.setEntity("execution", execution);
    query.setLockMode("task", LockMode.NONE);

    List<TaskImpl> tasks = query.list();
    for (TaskImpl task : tasks) {
        task.resume();
    }
}

From source file:org.jbpm.pvm.internal.hibernate.DbSessionImpl.java

License:Open Source License

public TaskImpl findTaskByExecution(Execution execution) {
    Query query = session.createQuery("select task " + "from " + TaskImpl.class.getName() + " as task "
            + "where task.execution = :execution");
    query.setEntity("execution", execution);
    query.setLockMode("task", LockMode.NONE);

    return (TaskImpl) query.uniqueResult();
}

From source file:org.jbpm.pvm.internal.hibernate.DbSessionImpl.java

License:Open Source License

public List<JobImpl<?>> findExclusiveJobs(Execution processInstance) {
    Query query = session.getNamedQuery("findExclusiveJobs");
    query.setTimestamp("now", Clock.getCurrentTime());
    query.setLockMode("job", LockMode.NONE);

    query.setEntity("processInstance", processInstance);
    return query.list();
}

From source file:org.jbpm.pvm.internal.jobexecutor.JobExecutorTimerSession.java

License:Open Source License

public List<Timer> findTimersByExecution(Execution execution) {
    Query query = session.createQuery("select timer " + "from " + TimerImpl.class.getName() + " timer "
            + "where timer.execution = :execution");
    query.setEntity("execution", execution);
    return query.list();
}

From source file:org.jpos.gl.GLSession.java

License:Open Source License

public void deleteBalanceCache(Journal journal, Account account, short[] layers) throws HibernateException {
    StringBuilder sb = new StringBuilder("delete BalanceCache where journal = :journal");
    if (account != null)
        sb.append(" and account = :account");
    if (layers != null)
        sb.append(" and layers = :layers");

    Query query = session.createQuery(sb.toString()).setEntity("journal", journal);
    if (account != null)
        query.setEntity("account", account);
    if (layers != null)
        query.setString("layers", layersToString(layers));

    query.executeUpdate();/* w  ww . j  a  va2s .c o  m*/
}

From source file:org.nextframework.persistence.SaveOrUpdateStrategy.java

License:Open Source License

/**
 * Deleta do banco as propriedades que nao foram encontrados no objeto
 * //w  ww.j av  a  2 s  . c o  m
 * @param path Nome da propriedade com a coleo
 * @param parentProperty Nome da propriedade nas classes filhas que fazem referencia a entidade
 * @param itemClass Classe dos itens da colecao indicada por path
 * @param insertFirst Se for true d preferencia a esse comando na hora de executar
 * @param collectionItemDeleteListener Listener que ser executado para cada objeto excluido (No ser feita excluso em batch se listener != null)
 * @return
 */
private SaveOrUpdateStrategy deleteNotInEntity(String path, final String parentProperty,
        final Class<?> itemClass, boolean insertFirst,
        final CollectionItemDeleteListener collectionItemDeleteListener) {
    try {
        Serializable entityid = PersistenceUtils.getId(entity, hibernateTemplate.getSessionFactory());
        if (entityid == null) {
            // se a entidade ainda nao est no banco nao existe nenhuma entidade no banco que nao esteje 
            // na propriedade
            return this;
        }

        //         ReflectionCache reflectionCache = ReflectionCacheFactory.getReflectionCache();
        //         Method method = reflectionCache.getMethod(entity.getClass(), "get"+StringUtils.capitalize(path));
        final Collection<?> collection = (Collection<?>) PersistenceUtils.getProperty(entity, path);
        //Query deleteQuery = null;
        HibernateCommand deleteCallback;
        if ((collection == null || collection.size() == 0) && collectionItemDeleteListener == null) {
            final String deleteQueryString = new StringBuilder().append("delete ").append(itemClass.getName())
                    .append(" where ").append(parentProperty).append(" = :")
                    .append(entity.getClass().getSimpleName()).toString();
            deleteCallback = new HibernateCommand() {
                public Object doInHibernate(Session session) throws HibernateException {
                    Query queryObject = session.createQuery(deleteQueryString);
                    queryObject.setEntity(entity.getClass().getSimpleName(), entity);
                    queryObject.executeUpdate();
                    return null;
                }
            };

        } else {
            //            final ClassMetadata metadata = hibernateTemplate.getSessionFactory().getClassMetadata(itemClass);
            //final List<Serializable> ids = new ArrayList<Serializable>();
            final List<?> toDelete = findItensToDelete(parentProperty, itemClass, collection);
            if (toDelete.size() == 0) {
                return this;
            }
            deleteCallback = new HibernateCommand() {
                public Object doInHibernate(final Session session) throws HibernateException {
                    //session = session.getSession(EntityMode.POJO);
                    //Transaction transaction = session.beginTransaction();

                    for (final Object object : toDelete) {
                        SaveOrUpdateStrategyChain chain = new SaveOrUpdateStrategyChain() {
                            public void execute() {
                                session.delete(object);
                            }
                        };
                        if (collectionItemDeleteListener != null) {
                            collectionItemDeleteListener.onDelete(object, chain);
                        } else {
                            chain.execute();
                        }
                        //session.flush();
                    }
                    //session.flush();
                    //transaction.commit();
                    return null;
                }
            };

        }
        if (insertFirst) {
            firstCallbacks.add(deleteCallback);
        } else {
            callbacks.add(deleteCallback);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return this;
}

From source file:org.nextframework.persistence.SaveOrUpdateStrategy.java

License:Open Source License

private List<?> findItensToDelete(final String parentProperty, final Class<?> itemClass,
        final Collection<?> collection) {
    final List<?> toDelete = (List<?>) hibernateTemplate.execute(new HibernateCommand() {
        public Object doInHibernate(Session session) {

            // remover dessa lista os objetos transientes
            Collection<Object> itens = new ArrayList<Object>(
                    collection == null ? new ArrayList<Object>() : collection);
            for (Iterator<Object> iter = itens.iterator(); iter.hasNext();) {
                Object entity = iter.next();
                Serializable id = PersistenceUtils.getId(entity, hibernateTemplate.getSessionFactory());
                if (id == null) {
                    iter.remove();/* w  ww  . ja  v a2 s. co  m*/
                }
            }
            if (itens.size() == 0) {
                // se nao tiver itens remover os que estiverem no banco
                final String findQueryString = new StringBuilder().append("from ").append(itemClass.getName())
                        .append(" ").append(uncapitalize(itemClass.getSimpleName())).append(" where ")
                        .append(uncapitalize(itemClass.getSimpleName())).append('.').append(parentProperty)
                        .append(" = :").append(entity.getClass().getSimpleName()).toString();

                Query q = session.createQuery(findQueryString);
                q.setEntity(entity.getClass().getSimpleName(), entity);
                return q.list();
            } else {
                boolean compositeParentProperty = parentProperty.indexOf('.') > 0;
                if (compositeParentProperty) {
                    // remover apenas os que nao estao na lista
                    // when the property is composite.. 
                    // must load all details and find manually the ones to delete 
                    final String findQueryString = new StringBuilder().append("from ")
                            .append(itemClass.getName()).append(" ")
                            .append(uncapitalize(itemClass.getSimpleName())).append(" where ")
                            .append(uncapitalize(itemClass.getSimpleName())).append('.').append(parentProperty)
                            .append(" = :").append(entity.getClass().getSimpleName()).toString();

                    Query q = session.createQuery(findQueryString);
                    q.setEntity(entity.getClass().getSimpleName(), entity);
                    List<?> databaseItems = q.list();
                    return PersistenceUtils.removeFromCollectionUsingId(session.getSessionFactory(),
                            databaseItems, itens);
                } else {
                    // remover apenas os que nao estao na lista
                    final String findQueryString = new StringBuilder().append("from ")
                            .append(itemClass.getName()).append(" ")
                            .append(uncapitalize(itemClass.getSimpleName())).append(" where ")
                            .append(uncapitalize(itemClass.getSimpleName()))
                            .append(" not in (:collection)  and ")
                            .append(uncapitalize(itemClass.getSimpleName())).append('.').append(parentProperty)
                            .append(" = :").append(entity.getClass().getSimpleName()).toString();

                    Query q = session.createQuery(findQueryString);
                    q.setParameterList("collection", itens);
                    q.setEntity(entity.getClass().getSimpleName(), entity);
                    return q.list();
                }
            }

        }

    });
    return toDelete;
}

From source file:org.openbravo.costing.CostingMigrationProcess.java

License:Open Source License

private void doChecks() {
    // Check all transactions have a legacy cost available.
    AlertRule legacyCostAvailableAlert = getLegacyCostAvailableAlert();
    if (legacyCostAvailableAlert == null) {
        Organization org0 = OBDal.getInstance().get(Organization.class, "0");
        Client client0 = OBDal.getInstance().get(Client.class, "0");

        legacyCostAvailableAlert = OBProvider.getInstance().get(AlertRule.class);
        legacyCostAvailableAlert.setClient(client0);
        legacyCostAvailableAlert.setOrganization(org0);
        legacyCostAvailableAlert.setName(alertRuleName);
        // Header tab of Product window
        legacyCostAvailableAlert.setTab(OBDal.getInstance().get(org.openbravo.model.ad.ui.Tab.class, "180"));
        StringBuffer sql = new StringBuffer();
        sql.append("select t.m_product_id as referencekey_id, '0' as ad_role_id, null as ad_user_id,");
        sql.append("\n    'Product ' || p.name || ' has transactions on dates without available");
        sql.append(" costs. Min date ' || min(t.movementdate) || '. Max date ' || max(t.movementdate)");
        sql.append(" as description,");
        sql.append("\n    'Y' as isactive, p.ad_org_id, p.ad_client_id,");
        sql.append("\n    now() as created, '0' as createdby, now() as updated, '0' as updatedby,");
        sql.append("\n    p.name as record_id");
        sql.append("\nfrom m_transaction t join m_product p on t.m_product_id = p.m_product_id");
        sql.append("\nwhere not exists (select 1 from m_costing c ");
        sql.append("\n                  where t.isactive = 'Y'");
        sql.append("\n                    and t.m_product_id = c.m_product_id");
        sql.append("\n                    and t.movementdate >= c.datefrom");
        sql.append("\n                    and t.movementdate < c.dateto");
        sql.append("\n                    and c.cost is not null)");
        sql.append("\ngroup by t.m_product_id, p.ad_org_id, p.ad_client_id, p.name");
        legacyCostAvailableAlert.setSql(sql.toString());

        OBDal.getInstance().save(legacyCostAvailableAlert);
        OBDal.getInstance().flush();/*from  w  w  w.  j a va 2  s.com*/

        insertAlertRecipients(legacyCostAvailableAlert);
    }

    // Delete previous alerts
    StringBuffer delete = new StringBuffer();
    delete.append("delete from " + Alert.ENTITY_NAME);
    delete.append(" where " + Alert.PROPERTY_ALERTRULE + " = :alertRule ");
    Query queryDelete = OBDal.getInstance().getSession().createQuery(delete.toString());
    queryDelete.setEntity("alertRule", legacyCostAvailableAlert);
    queryDelete.executeUpdate();

    if (legacyCostAvailableAlert.isActive()) {

        SQLQuery alertQry = OBDal.getInstance().getSession().createSQLQuery(legacyCostAvailableAlert.getSql());
        alertQry.addScalar("REFERENCEKEY_ID", StringType.INSTANCE);
        alertQry.addScalar("AD_ROLE_ID", StringType.INSTANCE);
        alertQry.addScalar("AD_USER_ID", StringType.INSTANCE);
        alertQry.addScalar("DESCRIPTION", StringType.INSTANCE);
        alertQry.addScalar("ISACTIVE", StringType.INSTANCE);
        alertQry.addScalar("AD_ORG_ID", StringType.INSTANCE);
        alertQry.addScalar("AD_CLIENT_ID", StringType.INSTANCE);
        alertQry.addScalar("CREATED", DateType.INSTANCE);
        alertQry.addScalar("CREATEDBY", StringType.INSTANCE);
        alertQry.addScalar("UPDATED", DateType.INSTANCE);
        alertQry.addScalar("UPDATEDBY", StringType.INSTANCE);
        alertQry.addScalar("RECORD_ID", StringType.INSTANCE);
        List<?> rows = alertQry.list();
        for (final Object row : rows) {
            final Object[] values = (Object[]) row;
            Alert alert = OBProvider.getInstance().get(Alert.class);
            alert.setCreatedBy(OBDal.getInstance().get(User.class, "0"));
            alert.setUpdatedBy(OBDal.getInstance().get(User.class, "0"));
            alert.setClient(OBDal.getInstance().get(Client.class, values[6]));
            alert.setOrganization(OBDal.getInstance().get(Organization.class, values[5]));
            alert.setAlertRule(legacyCostAvailableAlert);
            alert.setRecordID((String) values[11]);
            alert.setReferenceSearchKey((String) values[0]);
            alert.setDescription((String) values[3]);
            alert.setUserContact(null);
            alert.setRole(OBDal.getInstance().get(org.openbravo.model.ad.access.Role.class, "0"));
            OBDal.getInstance().save(alert);
        }
        if (SessionHandler.isSessionHandlerPresent()) {
            SessionHandler.getInstance().commitAndStart();
        }
        if (rows.size() > 0) {
            throw new OBException("@TrxWithNoCost@");
        }
    }
}