Example usage for org.hibernate Criteria setReadOnly

List of usage examples for org.hibernate Criteria setReadOnly

Introduction

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

Prototype

public Criteria setReadOnly(boolean readOnly);

Source Link

Document

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

Usage

From source file:com.zapangtrainer.model.dao.ClientDAOImpl.java

@Transactional(propagation = Propagation.REQUIRED, readOnly = true)
public Object readInnerPropertyToday(String type, String paramId, String date, String calType) {
    String average = null;//from ww  w  .  j a  v a  2  s  .  c o  m
    List<Reply> list = null;
    switch (type) {
    case "rating":

        session = getSessionFactory().openSession();

        Criteria criteria = session.createCriteria(Reply.class, "reply");
        criteria.createAlias("reply.client", "client");
        criteria.setReadOnly(true);
        criteria.add(Restrictions.eq("client.date", date));
        criteria.add(Restrictions.eq("reply.question", paramId));
        criteria.add(Restrictions.eq("reply.type", type));
        list = (List<Reply>) criteria.list();

        Float value = 0.0f;
        for (Reply val : list) {
            if (val.getAnswer() != null && !val.equals("")) {
                value += Float.parseFloat(val.getAnswer());
            }
        }
        value /= list.size();
        average = value.toString();

    case "descriptive":
    case "options":
    case "binary":
    default:
    }
    return average;
}

From source file:com.zapangtrainer.model.dao.ClientDAOImpl.java

@Transactional(propagation = Propagation.REQUIRED, readOnly = true)
public Long fetchEntitySizeToday() {
    Long size = 0l;//from   www .  j a  va2s  . com
    session = getSessionFactory().getCurrentSession();

    Criteria criteria = session.createCriteria(Client.class, "call");
    criteria.setReadOnly(true);
    criteria.add(
            Restrictions.like("date", new SimpleDateFormat("yyyy-MM-dd").format(new Date()), MatchMode.START));
    criteria.setProjection(Projections.rowCount());
    size = (Long) criteria.uniqueResult();

    return size;
}

From source file:com.zapangtrainer.model.dao.ClientDAOImpl.java

@Transactional(propagation = Propagation.REQUIRED, readOnly = true)
public String fetchAvgByTypeAndDate(String type, String date) {
    String average = null;/* w w  w  .j a  va2  s. c  o m*/
    session = getSessionFactory().getCurrentSession();

    Criteria criteria = session.createCriteria(Reply.class, "reply");
    criteria.setReadOnly(true);
    criteria.createAlias("reply.client", "client");
    criteria.add(Restrictions.like("client.date", date, MatchMode.START));
    criteria.add(Restrictions.like("reply.question", type));
    criteria.add(Restrictions.ne("reply.answer", "0"));
    criteria.setResultTransformer(criteria.DISTINCT_ROOT_ENTITY);
    List<Reply> list = criteria.list();

    Float value = 0.0f;
    for (Reply val : list) {
        if (val.getAnswer() != null && !val.getAnswer().equals("")) {
            value += Float.parseFloat(val.getAnswer());
        }
    }
    value /= list.size();
    average = value.toString();

    return average;
}

From source file:com.zapangtrainer.model.dao.ClientDAOImpl.java

@Transactional(propagation = Propagation.REQUIRED, readOnly = true)
public Long getProm() {
    Long val = null;

    session = getSessionFactory().getCurrentSession();

    Criteria criteria = session.createCriteria(Reply.class, "reply");
    criteria.setReadOnly(true);
    criteria.add(Restrictions.like("reply.type", "rating"));
    criteria.add(Restrictions.ne("reply.answer", "0"));

    criteria.add(Restrictions.or(Restrictions.like("reply.answer", "4", MatchMode.START),
            Restrictions.like("reply.answer", "5", MatchMode.START)));
    criteria.setProjection(Projections.rowCount());
    val = (Long) criteria.uniqueResult();

    return val;
}

From source file:com.zapangtrainer.model.dao.ClientDAOImpl.java

@Transactional(propagation = Propagation.REQUIRED, readOnly = true)
public Long getPass() {
    Long val = null;

    session = getSessionFactory().getCurrentSession();

    Criteria criteria = session.createCriteria(Reply.class, "reply");
    criteria.setReadOnly(true);
    criteria.add(Restrictions.like("reply.type", "rating"));
    criteria.add(Restrictions.ne("reply.answer", "0"));
    criteria.add(Restrictions.or(Restrictions.like("reply.answer", "2", MatchMode.START),
            Restrictions.like("reply.answer", "3", MatchMode.START)));
    criteria.setProjection(Projections.rowCount());
    val = (Long) criteria.uniqueResult();

    return val;
}

From source file:com.zapangtrainer.model.dao.ClientDAOImpl.java

@Transactional(propagation = Propagation.REQUIRED, readOnly = true)
public Long getDet() {
    Long val = null;

    session = getSessionFactory().getCurrentSession();

    Criteria criteria = session.createCriteria(Reply.class, "reply");
    criteria.setReadOnly(true);
    criteria.add(Restrictions.like("reply.type", "rating"));
    criteria.add(Restrictions.ne("reply.answer", "0"));
    criteria.add(Restrictions.or(Restrictions.like("reply.answer", "0", MatchMode.START),
            Restrictions.like("reply.answer", "1", MatchMode.START)));
    criteria.setProjection(Projections.rowCount());
    val = (Long) criteria.uniqueResult();

    return val;
}

From source file:edu.ucsb.eucalyptus.cloud.ws.BlockStorage.java

License:Open Source License

/**
 * Checks to see if a new snapshot of size volSize will exceed the quota
 * @param volSize//from w w  w  . ja v  a  2  s.c  o  m
 * @return
 */
private boolean totalSnapshotSizeLimitExceeded(String snapshotId, int volSize) throws EucalyptusCloudException {

    int totalSnapshotSize = 0;
    EntityTransaction dbTrans = Entities.get(SnapshotInfo.class);
    Criteria query = Entities.createCriteria(SnapshotInfo.class);
    query.setReadOnly(true);

    //TODO: zhill, fix this logic by adding a size value to the snapshot record, should do the calculation on the DB
    // this will be very poor for performance as the number of snapshots increases.

    //Only look for snaps that are not failed and not error
    query.add(Restrictions
            .not(Restrictions.and(Restrictions.eq("status", StorageProperties.Status.failed.toString()),
                    Restrictions.eq("status", StorageProperties.Status.error.toString()))));
    try {
        List<SnapshotInfo> snapInfos = (List<SnapshotInfo>) query.list();
        for (SnapshotInfo sInfo : snapInfos) {
            try {
                totalSnapshotSize += blockManager.getSnapshotSize(sInfo.getSnapshotId());
            } catch (EucalyptusCloudException e) {
                LOG.error(e);
            }
        }
        int sizeLimitGB = WalrusInfo.getWalrusInfo().getStorageMaxTotalSnapshotSizeInGb();
        LOG.debug("Snapshot " + snapshotId + " checking snapshot total size of  " + totalSnapshotSize
                + " against limit of " + sizeLimitGB);
        return (totalSnapshotSize + volSize) > sizeLimitGB;
    } catch (final Throwable e) {
        LOG.error("Error finding total snapshot used size " + e.getMessage());
        throw new EucalyptusCloudException("Failed to check snapshot total size limit", e);
    } finally {
        if (dbTrans.isActive()) {
            dbTrans.rollback();
        }
    }

}

From source file:org.candlepin.gutterball.curator.ComplianceSnapshotCurator.java

License:Open Source License

/**
 * Retrieves an iterator over the compliance snapshots for the specified consumer.
 *
 * @param consumerUUID//from  ww w.  j  av a 2s . c o  m
 *  The UUID for the consumer for which to retrieve compliance snapshots.
 *
 * @param startDate
 *  The start date to use to filter snapshots retrieved. If specified, only snapshots occurring
 *  after the start date, and the snapshot immediately preceding it, will be retrieved.
 *
 * @param endDate
 *  The end date to use to filter snapshots retrieved. If specified, only snapshots occurring
 *  before the end date will be retrieved.
 *
 * @param pageRequest
 *  A PageRequest instance containing paging information from the request. If null, no paging
 *  will be performed.
 *
 * @return
 *  A Page instance containing an iterator over the snapshots for the specified consumer, and
 *  the paging information for the query.
 */
@SuppressWarnings("checkstyle:indentation")
public Page<Iterator<Compliance>> getSnapshotIteratorForConsumer(String consumerUUID, Date startDate,
        Date endDate, PageRequest pageRequest) {

    Page<Iterator<Compliance>> page = new Page<Iterator<Compliance>>();
    page.setPageRequest(pageRequest);

    Session session = this.currentSession();
    Criteria query = session.createCriteria(Compliance.class, "comp1");
    query.createAlias("comp1.consumer", "cons1");

    query.add(Restrictions.eq("cons1.uuid", consumerUUID));

    if (startDate != null) {
        DetachedCriteria subquery = DetachedCriteria.forClass(Compliance.class, "comp2");
        subquery.createAlias("comp2.consumer", "cons2");
        subquery.createAlias("cons2.consumerState", "state2");

        subquery.add(Restrictions.or(Restrictions.isNull("state2.deleted"),
                Restrictions.gt("state2.deleted", startDate)));

        subquery.add(Restrictions.lt("state2.created", startDate));
        subquery.add(Restrictions.eqProperty("cons2.uuid", "cons1.uuid"));
        subquery.add(Restrictions.lt("comp2.date", startDate));

        subquery.setProjection(Projections.projectionList().add(Projections.max("comp2.date")));

        query.add(Restrictions.disjunction().add(Restrictions.ge("comp1.date", startDate))
                .add(Subqueries.propertyEq("comp1.date", subquery)));
    }

    if (endDate != null) {
        query.add(Restrictions.le("comp1.date", endDate));
    }

    query.setCacheMode(CacheMode.IGNORE);
    query.setReadOnly(true);

    if (pageRequest != null && pageRequest.isPaging()) {
        page.setMaxRecords(this.getRowCount(query));

        query.setFirstResult((pageRequest.getPage() - 1) * pageRequest.getPerPage());
        query.setMaxResults(pageRequest.getPerPage());

        if (pageRequest.getSortBy() != null) {
            query.addOrder(
                    pageRequest.getOrder() == PageRequest.Order.ASCENDING ? Order.asc(pageRequest.getSortBy())
                            : Order.desc(pageRequest.getSortBy()));
        }
    }

    page.setPageData(new AutoEvictingColumnarResultsIterator<Compliance>(session,
            query.scroll(ScrollMode.FORWARD_ONLY), 0));

    return page;
}

From source file:org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsHibernateUtil.java

License:Apache License

/**
 * Populates criteria arguments for the given target class and arguments map
 *
 * @param grailsApplication the GrailsApplication instance
 * @param targetClass The target class//from   ww w. j a  va  2 s  .c  om
 * @param c The criteria instance
 * @param argMap The arguments map
 *
        
 */
@SuppressWarnings("rawtypes")
public static void populateArgumentsForCriteria(GrailsApplication grailsApplication, Class<?> targetClass,
        Criteria c, Map argMap) {
    Integer maxParam = null;
    Integer offsetParam = null;
    SimpleTypeConverter converter = new SimpleTypeConverter();
    if (argMap.containsKey(ARGUMENT_MAX)) {
        maxParam = converter.convertIfNecessary(argMap.get(ARGUMENT_MAX), Integer.class);
    }
    if (argMap.containsKey(ARGUMENT_OFFSET)) {
        offsetParam = converter.convertIfNecessary(argMap.get(ARGUMENT_OFFSET), Integer.class);
    }
    if (argMap.containsKey(ARGUMENT_FETCH_SIZE)) {
        c.setFetchSize(converter.convertIfNecessary(argMap.get(ARGUMENT_FETCH_SIZE), Integer.class));
    }
    if (argMap.containsKey(ARGUMENT_TIMEOUT)) {
        c.setTimeout(converter.convertIfNecessary(argMap.get(ARGUMENT_TIMEOUT), Integer.class));
    }
    if (argMap.containsKey(ARGUMENT_FLUSH_MODE)) {
        c.setFlushMode(converter.convertIfNecessary(argMap.get(ARGUMENT_FLUSH_MODE), FlushMode.class));
    }
    if (argMap.containsKey(ARGUMENT_READ_ONLY)) {
        c.setReadOnly(GrailsClassUtils.getBooleanFromMap(ARGUMENT_READ_ONLY, argMap));
    }
    String orderParam = (String) argMap.get(ARGUMENT_ORDER);
    Object fetchObj = argMap.get(ARGUMENT_FETCH);
    if (fetchObj instanceof Map) {
        Map fetch = (Map) fetchObj;
        for (Object o : fetch.keySet()) {
            String associationName = (String) o;
            c.setFetchMode(associationName, getFetchMode(fetch.get(associationName)));
        }
    }

    final String sort = (String) argMap.get(ARGUMENT_SORT);
    final String order = ORDER_DESC.equalsIgnoreCase(orderParam) ? ORDER_DESC : ORDER_ASC;
    final int max = maxParam == null ? -1 : maxParam;
    final int offset = offsetParam == null ? -1 : offsetParam;
    if (max > -1) {
        c.setMaxResults(max);
    }
    if (offset > -1) {
        c.setFirstResult(offset);
    }
    if (GrailsClassUtils.getBooleanFromMap(ARGUMENT_CACHE, argMap)) {
        c.setCacheable(true);
    }
    if (GrailsClassUtils.getBooleanFromMap(ARGUMENT_LOCK, argMap)) {
        c.setLockMode(LockMode.PESSIMISTIC_WRITE);
    } else {
        if (argMap.get(ARGUMENT_CACHE) == null) {
            cacheCriteriaByMapping(targetClass, c);
        }
    }
    if (sort != null) {
        boolean ignoreCase = true;
        Object caseArg = argMap.get(ARGUMENT_IGNORE_CASE);
        if (caseArg instanceof Boolean) {
            ignoreCase = (Boolean) caseArg;
        }
        addOrderPossiblyNested(grailsApplication, c, targetClass, sort, order, ignoreCase);
    } else {
        Mapping m = GrailsDomainBinder.getMapping(targetClass);
        if (m != null && !StringUtils.isBlank(m.getSort())) {
            addOrderPossiblyNested(grailsApplication, c, targetClass, m.getSort(), m.getOrder(), true);
        }
    }
}

From source file:org.grails.orm.hibernate.cfg.GrailsHibernateUtil.java

License:Apache License

/**
 * Populates criteria arguments for the given target class and arguments map
 *
 * @param datastore the GrailsApplication instance
 * @param targetClass The target class/*from   www. ja  v  a  2  s  . com*/
 * @param c The criteria instance
 * @param argMap The arguments map
 */
@SuppressWarnings("rawtypes")
public static void populateArgumentsForCriteria(AbstractHibernateDatastore datastore, Class<?> targetClass,
        Criteria c, Map argMap, ConversionService conversionService, boolean useDefaultMapping) {
    Integer maxParam = null;
    Integer offsetParam = null;
    if (argMap.containsKey(ARGUMENT_MAX)) {
        maxParam = conversionService.convert(argMap.get(ARGUMENT_MAX), Integer.class);
    }
    if (argMap.containsKey(ARGUMENT_OFFSET)) {
        offsetParam = conversionService.convert(argMap.get(ARGUMENT_OFFSET), Integer.class);
    }
    if (argMap.containsKey(ARGUMENT_FETCH_SIZE)) {
        c.setFetchSize(conversionService.convert(argMap.get(ARGUMENT_FETCH_SIZE), Integer.class));
    }
    if (argMap.containsKey(ARGUMENT_TIMEOUT)) {
        c.setTimeout(conversionService.convert(argMap.get(ARGUMENT_TIMEOUT), Integer.class));
    }
    if (argMap.containsKey(ARGUMENT_FLUSH_MODE)) {
        c.setFlushMode(convertFlushMode(argMap.get(ARGUMENT_FLUSH_MODE)));
    }
    if (argMap.containsKey(ARGUMENT_READ_ONLY)) {
        c.setReadOnly(ClassUtils.getBooleanFromMap(ARGUMENT_READ_ONLY, argMap));
    }
    String orderParam = (String) argMap.get(ARGUMENT_ORDER);
    Object fetchObj = argMap.get(ARGUMENT_FETCH);
    if (fetchObj instanceof Map) {
        Map fetch = (Map) fetchObj;
        for (Object o : fetch.keySet()) {
            String associationName = (String) o;
            c.setFetchMode(associationName, getFetchMode(fetch.get(associationName)));
        }
    }

    final int max = maxParam == null ? -1 : maxParam;
    final int offset = offsetParam == null ? -1 : offsetParam;
    if (max > -1) {
        c.setMaxResults(max);
    }
    if (offset > -1) {
        c.setFirstResult(offset);
    }
    if (ClassUtils.getBooleanFromMap(ARGUMENT_LOCK, argMap)) {
        c.setLockMode(LockMode.PESSIMISTIC_WRITE);
        c.setCacheable(false);
    } else {
        if (argMap.containsKey(ARGUMENT_CACHE)) {
            c.setCacheable(ClassUtils.getBooleanFromMap(ARGUMENT_CACHE, argMap));
        } else {
            cacheCriteriaByMapping(targetClass, c);
        }
    }

    final Object sortObj = argMap.get(ARGUMENT_SORT);
    if (sortObj != null) {
        boolean ignoreCase = true;
        Object caseArg = argMap.get(ARGUMENT_IGNORE_CASE);
        if (caseArg instanceof Boolean) {
            ignoreCase = (Boolean) caseArg;
        }
        if (sortObj instanceof Map) {
            Map sortMap = (Map) sortObj;
            for (Object sort : sortMap.keySet()) {
                final String order = ORDER_DESC.equalsIgnoreCase((String) sortMap.get(sort)) ? ORDER_DESC
                        : ORDER_ASC;
                addOrderPossiblyNested(datastore, c, targetClass, (String) sort, order, ignoreCase);
            }
        } else {
            final String sort = (String) sortObj;
            final String order = ORDER_DESC.equalsIgnoreCase(orderParam) ? ORDER_DESC : ORDER_ASC;
            addOrderPossiblyNested(datastore, c, targetClass, sort, order, ignoreCase);
        }
    } else if (useDefaultMapping) {
        Mapping m = GrailsDomainBinder.getMapping(targetClass);
        if (m != null) {
            Map sortMap = m.getSort().getNamesAndDirections();
            for (Object sort : sortMap.keySet()) {
                final String order = ORDER_DESC.equalsIgnoreCase((String) sortMap.get(sort)) ? ORDER_DESC
                        : ORDER_ASC;
                addOrderPossiblyNested(datastore, c, targetClass, (String) sort, order, true);
            }
        }
    }
}