Example usage for org.hibernate CacheMode GET

List of usage examples for org.hibernate CacheMode GET

Introduction

In this page you can find the example usage for org.hibernate CacheMode GET.

Prototype

CacheMode GET

To view the source code for org.hibernate CacheMode GET.

Click Source Link

Document

The session may read items from the cache, but will not add items, except to invalidate items when updates occur.

Usage

From source file:com.sap.data.db.dao.StructureDao.java

public List<?> selectByJCO_USER(String jCo_USer) throws NotFoundException {
    List<?> list = null;//from w  w  w .j a v  a 2  s .c om
    Session session = null;
    try {
        session = HibernateUtil.getSession();
        session.setCacheMode(CacheMode.GET);
        list = session.createCriteria(this.structure).add(Restrictions.eq("DId.JCO_USER", jCo_USer)).list();
    } catch (HibernateException ex) {
        Logger.getLogger(StructureDao.class.getName()).log(Level.SEVERE, null, ex);
        throw new NotFoundException(ex.getMessage());
    } finally {
        HibernateUtil.close(session);
    }
    return list;
}

From source file:com.sap.data.db.dao.StructureDao.java

public int countSize() throws NotFoundException {
    int querySize = 0;
    Session session = null;/* w  w w  .  jav a  2  s .  c  om*/
    try {
        session = HibernateUtil.getSession();
        session.setCacheMode(CacheMode.GET);
        Query query = session.createQuery("select count(o) from " + this.structure + " o");
        querySize = ((Long) query.iterate().next()).intValue();
    } catch (HibernateException | IllegalArgumentException ex) {
        Logger.getLogger(StructureDao.class.getName()).log(Level.SEVERE, null, ex);
        throw new NotFoundException(ex.getMessage());
    } finally {
        HibernateUtil.close(session);
    }
    return querySize;
}

From source file:de.innovationgate.webgate.api.jdbc.WGDatabaseImpl.java

License:Open Source License

public boolean beginTransaction() throws WGAPIException {
    Transaction transaction = getSession().getTransaction();
    if (transaction != null && transaction.isActive()) {
        transaction.rollback();/*w  w  w . j a va  2  s  .  c o m*/
    }
    transaction = getSession().beginTransaction();
    if (transaction != null) {
        getSession().setCacheMode(CacheMode.GET);
        _db.getSessionContext().setTransactionMode(WGSessionContext.TRANSACTION_MODE_MANUAL);
        return true;
    } else {
        return false;
    }
}

From source file:de.iteratec.iteraplan.businesslogic.exchange.elasticeam.IteraplanMetamodelAndModelLoader.java

License:Open Source License

@Override
public MetamodelAndModelContainer call() throws ElasticeamException {
    MetamodelAndModelContainer result = null;

    try {/* ww  w  . ja va2s . c  o m*/
        //Create a temporary user context to avoid errors
        createTempUserContext();

        //Open a new session
        Session session = SessionFactoryUtils.getSession(hibernateAccessor.getSessionFactory(),
                hibernateAccessor.getEntityInterceptor(), hibernateAccessor.getJdbcExceptionTranslator());
        session.setFlushMode(FlushMode.MANUAL);
        session.setCacheMode(CacheMode.GET);
        SessionHolder sessionHolder = null;

        try {
            hibernateAccessor.applyFlushMode(session, false);
            sessionHolder = new SessionHolder(session);
            TransactionSynchronizationManager.bindResource(hibernateAccessor.getSessionFactory(),
                    sessionHolder);
            Transaction t = hibernateAccessor.getSessionFactory().getCurrentSession().beginTransaction();
            try {

                //Once the session has been opened, trigger the actual model and data loading in the superclass
                result = super.call();

                //After model and data have been loaded, close the session.
                t.commit();
            } catch (HibernateException e) {
                t.rollback();
                throw new ElasticeamException(ElasticeamException.GENERAL_ERROR,
                        "IteraQl model and data could not be loaded in iteraplan due to an exception in hibernate: \n "
                                + e);
            }
        } finally {
            SessionFactoryUtils.closeSession(sessionHolder.getSession());
            TransactionSynchronizationManager.unbindResource(hibernateAccessor.getSessionFactory());
        }

        //Remove the temporary user context
        UserContext.detachCurrentUserContext();

    } catch (Exception ex) {
        LOGGER.error("IteraQl model and data loading failed", ex);
        throw new ElasticeamException(ElasticeamException.GENERAL_ERROR,
                "IteraQl model and data loading failed: \n" + ex, ex);
    }
    return result;
}

From source file:de.iteratec.iteraplan.businesslogic.exchange.elasticmi.IteraplanMiLoadTask.java

License:Open Source License

@Override
public SimpleM3C call() {

    SimpleM3C result = null;/*from  ww w  .j ava 2  s.  c o  m*/
    if (UserContext.getCurrentUserContext() != null) {
        try {
            result = super.call();
        } catch (Exception ex) {
            LOGGER.error("IteraQl model and data loading failed", ex);
            throw new ElasticMiException(ElasticMiException.GENERAL_ERROR,
                    "IteraQl model and data loading failed: \n" + ex, ex);
        }
    } else {
        try {
            //Create a temporary user context to avoid errors
            createTempUserContext();

            //Open a new session
            Session session = SessionFactoryUtils.getSession(hibernateAccessor.getSessionFactory(),
                    hibernateAccessor.getEntityInterceptor(), hibernateAccessor.getJdbcExceptionTranslator());
            session.setFlushMode(FlushMode.MANUAL);
            session.setCacheMode(CacheMode.GET);
            SessionHolder sessionHolder = null;

            try {
                hibernateAccessor.applyFlushMode(session, false);
                sessionHolder = new SessionHolder(session);
                TransactionSynchronizationManager.bindResource(hibernateAccessor.getSessionFactory(),
                        sessionHolder);
                Transaction t = hibernateAccessor.getSessionFactory().getCurrentSession().beginTransaction();
                try {

                    //Once the session has been opened, trigger the actual model and data loading in the superclass
                    result = super.call();
                    //After model and data have been loaded, close the session.
                    t.commit();
                } catch (HibernateException e) {
                    t.rollback();
                    throw new ElasticMiException(ElasticMiException.GENERAL_ERROR,
                            "IteraQl model and data could not be loaded in iteraplan due to an exception in hibernate: \n "
                                    + e);
                }
            } finally {
                SessionFactoryUtils.closeSession(sessionHolder.getSession());
                TransactionSynchronizationManager.unbindResource(hibernateAccessor.getSessionFactory());
            }

        } catch (Exception ex) {
            LOGGER.error("IteraQl model and data loading failed", ex);
            throw new ElasticMiException(ElasticMiException.GENERAL_ERROR,
                    "IteraQl model and data loading failed: \n" + ex, ex);
        } finally {
            //Remove the temporary user context
            UserContext.detachCurrentUserContext();
        }
    }
    return result;
}

From source file:es.tid.fiware.iot.ac.pdp.PdpEndpoint.java

License:Apache License

@POST
@UnitOfWork(readOnly = true, transactional = false, cacheMode = CacheMode.GET, flushMode = FlushMode.MANUAL)
@Timed//from ww w  .  ja  va  2  s .co  m
public Response enforce(@Tenant String tenant, String xacmlRequest) {

    LOGGER.debug("Enforcing policies for tenant [{}]", tenant);
    LOGGER.trace("XACML Request: {}", xacmlRequest);

    PDP pdp = pdpFactory.get(tenant, extractSubjectIds(xacmlRequest));
    return Response.ok(pdp.evaluate(xacmlRequest)).build();
}

From source file:org.alfresco.repo.workflow.jbpm.JBPMEngine.java

License:Open Source License

@SuppressWarnings("unchecked")
public List<WorkflowInstance> cancelWorkflows(final List<String> workflowIds) {
    return (List<WorkflowInstance>) jbpmTemplate.execute(new JbpmCallback() {
        public Object doInJbpm(JbpmContext context) {
            // Bypass the cache making sure not to flush it
            Session session = context.getSession();
            CacheMode cacheMode = session.getCacheMode();
            FlushMode flushMode = session.getFlushMode();
            session.setCacheMode(CacheMode.GET);
            session.setFlushMode(FlushMode.MANUAL);
            try {
                List<WorkflowInstance> workflowInstances = new ArrayList<WorkflowInstance>(workflowIds.size());
                Map<String, ProcessInstance> processInstances = new HashMap<String, ProcessInstance>(
                        workflowIds.size() * 2);
                GraphSession graphSession = context.getGraphSession();

                // retrieve and cancel process instances
                for (String workflowId : workflowIds) {
                    try {
                        ProcessInstance processInstance = getProcessInstance(graphSession, workflowId);
                        processInstance.getContextInstance().setVariable("cancelled", true);
                        processInstance.end();
                        processInstances.put(workflowId, processInstance);
                    } catch (JbpmException e) {
                        String msg = messageService.getMessage(ERR_CANCEL_WORKFLOW, workflowId);
                        throw new WorkflowException(msg, JbpmAccessor.convertJbpmException(e));
                    }/*w  w w. java 2s  .  c  om*/
                }

                // Flush at the end of the batch
                session.flush();

                for (String workflowId : workflowIds) {
                    try {
                        // retrieve process instance
                        ProcessInstance processInstance = processInstances.get(workflowId);
                        // TODO: Determine if this is the most appropriate way to cancel workflow...
                        //       It might be useful to record point at which it was cancelled etc
                        try {
                            workflowInstances.add(createWorkflowInstance(processInstance));
                        } catch (Exception ex) {
                            logger.warn("Unable to load workflow instance: '" + processInstance
                                    + "' due to exception.", ex);
                        }

                        // delete the process instance
                        graphSession.deleteProcessInstance(processInstance, true, true);
                    } catch (JbpmException e) {
                        String msg = messageService.getMessage(ERR_CANCEL_WORKFLOW, workflowId);
                        throw new WorkflowException(msg, JbpmAccessor.convertJbpmException(e));
                    }
                }

                // Flush at the end of the batch
                session.flush();
                return workflowInstances;
            } finally {
                session.setCacheMode(cacheMode);
                session.setFlushMode(flushMode);
            }
        }
    });
}

From source file:org.alfresco.repo.workflow.jbpm.JBPMEngine.java

License:Open Source License

@SuppressWarnings("unchecked")
public List<WorkflowTask> queryTasks(final WorkflowTaskQuery query, final boolean sameSession) {
    try {//w w w . j  ava 2  s  . c  o  m
        return (List<WorkflowTask>) jbpmTemplate.execute(new JbpmCallback() {
            public List<WorkflowTask> doInJbpm(JbpmContext context) {
                // Bypass the cache making sure not to flush it
                Session session = context.getSession();
                CacheMode cacheMode = session.getCacheMode();
                try {
                    session.setCacheMode(CacheMode.GET);
                    Criteria criteria = createTaskQueryCriteria(session, query);
                    List<TaskInstance> tasks = criteria.list();
                    return getWorkflowTasks(tasks, sameSession);
                } finally {
                    session.setCacheMode(cacheMode);
                }
            }
        });
    } catch (JbpmException e) {
        String msg = messageService.getMessage(ERR_QUERY_TASKS, query);
        throw new WorkflowException(msg, e);
    }
}

From source file:org.alfresco.repo.workflow.jbpm.JBPMEngine.java

License:Open Source License

@SuppressWarnings("unchecked")
public List<WorkflowTask> getStartTasks(final List<String> workflowInstanceIds, final boolean sameSession) {
    try {//from   w ww . ja  va  2 s . c  om
        return (List<WorkflowTask>) jbpmTemplate.execute(new JbpmCallback() {
            public Object doInJbpm(JbpmContext context) {
                List<Long> jbpmIds = new ArrayList<Long>(workflowInstanceIds.size());
                Set<String> startTaskNames = new TreeSet<String>();
                for (String workflowInstanceId : workflowInstanceIds) {
                    // retrieve process instance
                    GraphSession graphSession = context.getGraphSession();
                    ProcessInstance processInstance = getProcessInstanceIfExists(graphSession,
                            workflowInstanceId);
                    if (processInstance != null) {
                        jbpmIds.add(processInstance.getId());
                        Task startTask = processInstance.getProcessDefinition().getTaskMgmtDefinition()
                                .getStartTask();
                        startTaskNames.add(startTask.getName());
                    }
                }

                if (jbpmIds.isEmpty()) {
                    return Collections.emptyList();
                }

                // retrieve tasks
                Session session = context.getSession();
                Criteria taskCriteria = session.createCriteria(TaskInstance.class);
                taskCriteria.add(Restrictions.in("name", startTaskNames));
                Criteria process = taskCriteria.createCriteria("processInstance");
                process.add(Restrictions.in("id", jbpmIds));

                // Bypass the cache making sure not to flush it
                CacheMode cacheMode = session.getCacheMode();
                try {
                    session.setCacheMode(CacheMode.GET);
                    List<TaskInstance> tasks = process.list();
                    return getWorkflowTasks(tasks, sameSession);
                } finally {
                    session.setCacheMode(cacheMode);
                }
            }
        });
    } catch (JbpmException e) {
        String msg = messageService.getMessage(ERR_QUERY_TASKS, workflowInstanceIds);
        throw new WorkflowException(msg, e);
    }
}

From source file:org.candlepin.model.DetachedCandlepinQuery.java

License:Open Source License

/**
 * {@inheritDoc}//from  w w  w .j  a  v  a 2  s  .  c o  m
 */
@Override
@Transactional
@SuppressWarnings("unchecked")
public int forEach(int column, boolean evict, ResultProcessor<T> processor) {
    if (processor == null) {
        throw new IllegalArgumentException("processor is null");
    }

    Criteria executable = this.getExecutableCriteria();

    // We always override the cache mode here to ensure we don't evict things that may be in
    // cache from another request.
    if (evict) {
        executable.setCacheMode(CacheMode.GET);
    }

    ScrollableResults cursor = executable.scroll(ScrollMode.FORWARD_ONLY);
    int count = 0;

    try {
        boolean cont = true;

        if (evict) {
            while (cont && cursor.next()) {
                T result = (T) cursor.get(column);

                cont = processor.process(result);
                this.session.evict(result);

                ++count;
            }
        } else {
            while (cont && cursor.next()) {
                cont = processor.process((T) cursor.get(column));
                ++count;
            }
        }
    } finally {
        cursor.close();
    }

    return count;
}