Example usage for org.hibernate Query setReadOnly

List of usage examples for org.hibernate Query setReadOnly

Introduction

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

Prototype

Query<R> setReadOnly(boolean readOnly);

Source Link

Document

Set the read-only/modifiable mode for entities and proxies loaded by this Query.

Usage

From source file:org.headsupdev.agile.storage.HibernateStorage.java

License:Open Source License

public List<Event> getEventsForUser(User user, Date start, Date stop) {
    Session session = getHibernateSession();
    Transaction tx = session.beginTransaction();

    Query q = session.createQuery("from StoredEvent e where time >= :start and time < :end and "
            + "(username = :username or username like :emailLike or username like :nameLike) order by time desc");
    q.setTimestamp("start", start);
    q.setTimestamp("end", stop);
    q.setString("username", user.getUsername());

    if (!StringUtil.isEmpty(user.getEmail())) {
        q.setString("emailLike", "%<" + user.getEmail() + ">");
    } else {//from  w w  w  .j av  a  2  s.  c om
        // a silly fallback for now
        q.setString("emailLike", user.getUsername());
    }

    if (!StringUtil.isEmpty(user.getFullname())) {
        q.setString("nameLike", user.getFullname() + " <%");
    } else {
        // a silly fallback for now
        q.setString("nameLike", user.getUsername());
    }

    q.setReadOnly(true);
    List<Event> list = q.list();
    tx.commit();

    return list;
}

From source file:org.jboss.aerogear.unifiedpush.jpa.dao.impl.JPAInstallationDao.java

License:Apache License

@Override
public ResultsStream.QueryBuilder<String> findAllDeviceTokenForVariantIDByCriteria(String variantID,
        List<String> categories, List<String> aliases, List<String> deviceTypes, final int maxResults,
        String lastTokenFromPreviousBatch) {
    // the required part: Join + all tokens for variantID;

    final StringBuilder jpqlString = new StringBuilder(FIND_ALL_DEVICES_FOR_VARIANT_QUERY);
    final Map<String, Object> parameters = new LinkedHashMap<String, Object>();
    parameters.put("variantID", variantID);

    // apend query conditions based on specified message parameters
    appendDynamicQuery(jpqlString, parameters, categories, aliases, deviceTypes);

    // sort on ids so that we can handle paging properly
    if (lastTokenFromPreviousBatch != null) {
        jpqlString.append(" AND installation.deviceToken > :lastTokenFromPreviousBatch");
        parameters.put("lastTokenFromPreviousBatch", lastTokenFromPreviousBatch);
    }//ww w .  ja v a  2  s .  co m

    jpqlString.append(" ORDER BY installation.deviceToken ASC");

    return new ResultsStream.QueryBuilder<String>() {
        private Integer fetchSize = null;

        @Override
        public ResultsStream.QueryBuilder<String> fetchSize(int fetchSize) {
            this.fetchSize = fetchSize;
            return this;
        }

        @Override
        public ResultsStream<String> executeQuery() {
            Query hibernateQuery = JPAInstallationDao.this.createHibernateQuery(jpqlString.toString());
            hibernateQuery.setMaxResults(maxResults);
            for (Entry<String, Object> parameter : parameters.entrySet()) {
                Object value = parameter.getValue();
                if (value instanceof Collection<?>) {
                    hibernateQuery.setParameterList(parameter.getKey(), (Collection<?>) parameter.getValue());
                } else {
                    hibernateQuery.setParameter(parameter.getKey(), parameter.getValue());
                }

            }
            hibernateQuery.setReadOnly(true);
            if (fetchSize != null) {
                hibernateQuery.setFetchSize(fetchSize);
            }
            final ScrollableResults results = hibernateQuery.scroll(ScrollMode.FORWARD_ONLY);
            return new ResultsStream<String>() {
                @Override
                public boolean next() throws ResultStreamException {
                    return results.next();
                }

                @Override
                public String get() throws ResultStreamException {
                    return (String) results.get()[0];
                }
            };
        }

    };
}

From source file:org.kimios.kernel.dms.hibernate.HWorkspaceFactory.java

License:Open Source License

public List<Workspace> getWorkspaces() throws ConfigException, DataSourceException {
    try {//from  w w  w  .  ja va  2s  . c om
        //Criteria c = getSession().createCriteria(Workspace.class).addOrder(Order.asc("name").ignoreCase());
        Query q = getSession().createQuery("from Workspace w order by w.name");
        List<Workspace> wList = q.setReadOnly(true).setFetchSize(100).list();
        return wList;
    } catch (HibernateException e) {
        throw new DataSourceException(e);
    }
}

From source file:org.ng200.openolympus.services.TaskService.java

License:Open Source License

@PreAuthorize(SecurityExpressionConstants.IS_ADMIN)
@Transactional/*from   ww w.j a v  a2s . c om*/
public void rejudgeTask(final Task task) throws ExecutionException, IOException {

    final Lock lock = task.writeLock();
    lock.lock();

    try {

        this.verdictRepository.flush();
        this.solutionRepository.flush();

        this.verdictRepository.deleteBySolutionTask(task);
        this.verdictRepository.flush();

        final StatelessSession session = ((Session) this.entityManager.getDelegate()).getSessionFactory()
                .openStatelessSession();
        try {
            final Query query = session.createQuery("from Solution where task_id=:taskID");
            query.setParameter("taskID", task.getId());
            query.setFetchSize(Integer.valueOf(1000));
            query.setReadOnly(false);
            final ScrollableResults results = query.scroll(ScrollMode.FORWARD_ONLY);
            try {
                while (results.next()) {
                    final Solution solution = (Solution) results.get(0);
                    this.testingService.testSolutionOnAllTests(solution);
                }
            } finally {
                results.close();
            }
        } finally {
            session.close();
        }
    } finally {
        lock.unlock();
    }
}

From source file:org.onecmdb.core.internal.storage.hibernate.HibernateDao.java

License:Open Source License

public List sqlQuery(String sql) {
    // Quering the db.
    Session session = getSession();/*from   ww w.  j a v  a  2  s  .co  m*/
    try {
        Query query = session.createSQLQuery(sql).addEntity("ci", ConfigurationItem.class);
        query.setReadOnly(true);
        List list = query.list();
        return (list);
    } finally {
        closeSession(session);
    }

}

From source file:org.onecmdb.core.internal.storage.hibernate.HibernateDao.java

License:Open Source License

public List hqlQuery(String hql) {
    // Quering the db.
    Session session = getSession();/*from w w w.  j  a va  2s . c  om*/
    try {
        Query query = session.createQuery(hql);
        query.setReadOnly(true);
        List list = query.list();
        return (list);
    } finally {
        closeSession(session);
    }

}

From source file:org.openbravo.erpCommon.ad_process.UpdateActuals.java

License:Open Source License

@Override
protected void doExecute(ProcessBundle bundle) throws Exception {
    final OBError msg = new OBError();

    try {/*  w  ww  .ja  v a  2  s  . co  m*/
        // retrieve the parameters from the bundle
        final String cBudgetId = (String) bundle.getParams().get("C_Budget_ID");

        String activity = null;
        String accountingSchema = null;
        String asset = null;
        String businessPartner = null;
        String businessPartnerCategory = null;
        String costcenter = null;
        String account = null;
        String accountSign = null;
        String period = null;
        String product = null;
        String productCategory = null;
        String project = null;
        String salesCampaign = null;
        String salesRegion = null;
        String user1 = null;
        String user2 = null;

        // Gets the budget lines
        Budget myBudget = OBDal.getInstance().get(Budget.class, cBudgetId);
        for (BudgetLine budgetLine : myBudget.getFinancialMgmtBudgetLineList()) {
            activity = (budgetLine.getActivity() != null) ? budgetLine.getActivity().getId() : "";
            accountingSchema = (budgetLine.getAccountingSchema() != null)
                    ? budgetLine.getAccountingSchema().getId()
                    : "";
            asset = (budgetLine.getAsset() != null) ? budgetLine.getAsset().getId() : "";
            businessPartner = (budgetLine.getBusinessPartner() != null)
                    ? budgetLine.getBusinessPartner().getId()
                    : "";
            businessPartnerCategory = (budgetLine.getBusinessPartnerCategory() != null)
                    ? budgetLine.getBusinessPartnerCategory().getId()
                    : "";
            costcenter = (budgetLine.getCostcenter() != null) ? budgetLine.getCostcenter().getId() : "";
            account = (budgetLine.getAccountElement() != null) ? budgetLine.getAccountElement().getId() : "";
            accountSign = (budgetLine.getAccountElement() != null)
                    ? budgetLine.getAccountElement().getAccountSign()
                    : "";
            period = (budgetLine.getPeriod() != null) ? budgetLine.getPeriod().getId() : "";
            product = (budgetLine.getProduct() != null) ? budgetLine.getProduct().getId() : "";
            productCategory = (budgetLine.getProductCategory() != null)
                    ? budgetLine.getProductCategory().getId()
                    : "";
            project = (budgetLine.getProject() != null) ? budgetLine.getProject().getId() : "";
            salesCampaign = (budgetLine.getSalesCampaign() != null) ? budgetLine.getSalesCampaign().getId()
                    : "";
            salesRegion = (budgetLine.getSalesRegion() != null) ? budgetLine.getSalesRegion().getId() : "";
            user1 = (budgetLine.getStDimension() != null) ? budgetLine.getStDimension().getId() : "";
            user2 = (budgetLine.getNdDimension() != null) ? budgetLine.getNdDimension().getId() : "";

            // get the natural tree
            TreeUtility treeUtility = new TreeUtility();
            String activityTree = activity != null
                    ? Utility.arrayListToString(
                            (new ArrayList<String>(treeUtility.getChildTree(activity, "AY", true))), true)
                    : activity;
            String productCategoryTree = productCategory != null ? Utility.arrayListToString(
                    (new ArrayList<String>(treeUtility.getChildTree(productCategory, "PC", true))), true)
                    : productCategory;
            String assetTree = asset != null ? Utility.arrayListToString(
                    (new ArrayList<String>(treeUtility.getChildTree(asset, "AS", true))), true) : asset;
            String costcenterTree = costcenter != null
                    ? Utility.arrayListToString(
                            (new ArrayList<String>(treeUtility.getChildTree(costcenter, "CC", true))), true)
                    : costcenter;
            String accountTree = account != null
                    ? Utility.arrayListToString(
                            (new ArrayList<String>(treeUtility.getChildTree(account, "EV", true))), true)
                    : account;
            String projectTree = project != null
                    ? Utility.arrayListToString(
                            new ArrayList<String>(treeUtility.getChildTree(project, "PJ", true)), true)
                    : project;
            String campaignTree = salesCampaign != null
                    ? Utility.arrayListToString(
                            new ArrayList<String>(treeUtility.getChildTree(salesCampaign, "MC", true)), true)
                    : salesCampaign;
            String regionTree = salesRegion != null
                    ? Utility.arrayListToString(
                            new ArrayList<String>(treeUtility.getChildTree(salesRegion, "SR", true)), true)
                    : salesRegion;
            String user1Tree = user1 != null ? Utility.arrayListToString(
                    (new ArrayList<String>(treeUtility.getChildTree(user1, "U1", true))), true) : user1;
            String user2Tree = user2 != null ? Utility.arrayListToString(
                    (new ArrayList<String>(treeUtility.getChildTree(user2, "U2", true))), true) : user2;

            final String orgId = myBudget.getOrganization().getId();
            ArrayList<String> organizationList = new ArrayList<String>(
                    OBContext.getOBContext().getOrganizationStructureProvider().getChildTree(orgId, true));
            String OrgTreeList = Utility.arrayListToString(organizationList, true);

            StringBuilder queryString = new StringBuilder();
            queryString.append("select SUM(e.credit) as credit,");
            queryString.append(" SUM(e.debit) as debit");
            queryString.append(" from FinancialMgmtAccountingFact e where");
            queryString.append(" e.client.id='").append(myBudget.getClient().getId()).append("'");
            queryString.append(" and e.organization.id in (").append(OrgTreeList).append(")");

            if (!"".equals(activity)) {
                queryString.append(" and e.activity.id in (").append(activityTree).append(")");
            }
            queryString.append(" and e.accountingSchema.id=:accountingSchema");
            if (!"".equals(asset)) {
                queryString.append(" and e.asset.id in (").append(assetTree).append(")");
            }
            if (!"".equals(businessPartner)) {
                queryString.append(" and e.businessPartner.id = :businessPartner");
            } else if (!"".equals(businessPartnerCategory)) {
                queryString.append(
                        " and exists (select 1 from BusinessPartner bp where businessPartnerCategory.id=:businessPartnerCategory)");
            }
            if (!"".equals(costcenter)) {
                queryString.append(" and e.costcenter.id in (").append(costcenterTree).append(")");
            }
            queryString.append(" and e.account.id in (").append(accountTree).append(")");
            if (!"".equals(period)) {
                queryString.append(" and e.period.id=:period");
            }
            if (!"".equals(product)) {
                queryString.append(" and e.product.id=:product");
            } else if (!"".equals(productCategory)) {
                queryString.append(" and exists (select 1 from Product p where productCategory.id in (")
                        .append(productCategoryTree).append("))");
            }
            if (!"".equals(project)) {
                queryString.append(" and e.project.id in (").append(projectTree).append(")");
            }
            if (!"".equals(salesCampaign)) {
                queryString.append(" and e.salesCampaign.id in (").append(campaignTree).append(")");
            }
            if (!"".equals(salesRegion)) {
                queryString.append(" and e.salesRegion.id in (").append(regionTree).append(")");
            }
            if (!"".equals(user1)) {
                queryString.append(" and e.stDimension.id in (").append(user1Tree).append(")");
            }
            if (!"".equals(user1)) {
                queryString.append(" and e.ndDimension.id in (").append(user2Tree).append(")");
            }
            Query query = OBDal.getInstance().getSession().createQuery(queryString.toString());
            query.setReadOnly(true);
            query.setString("accountingSchema", accountingSchema);
            if (!"".equals(businessPartner))
                query.setString("businessPartner", businessPartner);
            else if (!"".equals(businessPartnerCategory))
                query.setString("businessPartnerCategory", businessPartnerCategory);
            if (!"".equals(period))
                query.setString("period", period);
            if (!"".equals(product))
                query.setString("product", product);

            log4j.debug("Query String" + query.getQueryString());

            BigDecimal credit = BigDecimal.ZERO;
            BigDecimal debit = BigDecimal.ZERO;
            for (Object obj : query.list()) {
                if (obj != null) {
                    Object[] row = (Object[]) obj;
                    credit = (BigDecimal) ((row[0] != null) ? row[0] : new BigDecimal(0));
                    debit = (BigDecimal) ((row[1] != null) ? row[1] : new BigDecimal(0));
                }
            }

            if (("D").equals(accountSign)) {
                budgetLine.setActualAmount(debit.subtract(credit));
            } else {
                budgetLine.setActualAmount(credit.subtract(debit));
            }

            msg.setType("Success");
            msg.setTitle("Success");
            msg.setMessage("Actual Amount = " + budgetLine.getActualAmount());
            bundle.setResult(msg);
        }

    } catch (Exception e) {
        msg.setType("Error");
        msg.setTitle("Error");
        msg.setMessage(e.toString());
        bundle.setResult(msg);
        OBDal.getInstance().rollbackAndClose();
    } finally {
        OBDal.getInstance().commitAndClose();
    }
}

From source file:org.opencustomer.db.dao.calendar.EventCalendarDAO.java

License:Mozilla Public License

public List<EventCalendarVO> getByCalendar(CalendarVO calendar, boolean readonly) throws HibernateException {
    List<EventCalendarVO> l = null;
    try {//from  w  w w  . j av  a  2  s  .  c  o m
        StringBuilder hql = new StringBuilder();
        hql.append(" FROM ").append(getEntityClass().getName()).append(" e ");
        hql.append(" WHERE e.calendar = :calendar ");

        Query query = HibernateContext.getSession().createQuery(hql.toString());
        query.setReadOnly(readonly);
        query.setEntity("calendar", calendar);

        l = toTypeSafeList(query.list());
    } catch (HibernateException e) {
        log.error("Could eventCalendars by calendar", e);
        throw e;
    }

    return l;
}

From source file:org.openmrs.module.amrsreports.db.hibernate.MohHibernateCoreDAO.java

License:Open Source License

@Override
public List<Object> executeScrollingHqlQuery(String query, Map<String, Object> substitutions) {
    Query q = sessionFactory.getCurrentSession().createQuery(query);

    applySubstitutions(q, substitutions);

    // optimizations go here
    q.setFetchSize(Integer.MIN_VALUE);
    q.setReadOnly(true);

    List<Object> res = new ArrayList<Object>();

    long i = 0;//  w  ww.  j  a va2s . c  o  m

    ScrollableResults sr = q.scroll(ScrollMode.FORWARD_ONLY);
    while (sr.next()) {

        // rows always come back as an array
        Object[] o = sr.get();

        // but if there is only one object in the row, add it instead of the array
        if (o.length == 1)
            res.add(o[0]);
        else
            res.add(o);

        if (++i % 500 == 0)
            log.warn("processed #" + i);
    }

    log.warn("done. processed " + i + " total rows.");

    sr.close();

    return res;
}

From source file:org.openmrs.module.amrsreports.db.hibernate.MohHibernateCoreDAO.java

License:Open Source License

@Override
public List<Object> executeHqlQuery(String query, Map<String, Object> substitutions) {
    Query q = sessionFactory.getCurrentSession().createQuery(query);

    applySubstitutions(q, substitutions);

    // optimizations go here
    q.setReadOnly(true);

    return q.list();
}