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:edu.ur.hibernate.ir.user.db.HbExternalAccountTypeDAO.java

License:Apache License

/**
 * Get external account types ordered by name.
 * /*from w  w  w . java2 s  . co m*/
 * @see edu.ur.ir.user.ExternalAccountTypeDAO#getOrderByName(int, int, edu.ur.order.OrderType)
 */
@SuppressWarnings("unchecked")
public List<ExternalAccountType> getOrderByName(final int rowStart, final int numberOfResultsToShow,
        final OrderType orderType) {
    List<ExternalAccountType> externalAccountTypes = (List<ExternalAccountType>) hbCrudDAO
            .getHibernateTemplate().execute(new HibernateCallback() {
                public Object doInHibernate(Session session) throws HibernateException, SQLException {

                    Query q = null;
                    if (orderType.equals(OrderType.ASCENDING_ORDER)) {
                        q = session.getNamedQuery("getExternalAccountTypesOrderByNameAsc");
                    } else {
                        q = session.getNamedQuery("getExternalAccountTypesOrderByNameDesc");
                    }

                    q.setFirstResult(rowStart);
                    q.setMaxResults(numberOfResultsToShow);
                    q.setReadOnly(true);
                    q.setFetchSize(numberOfResultsToShow);
                    return q.list();
                }

            });

    return externalAccountTypes;
}

From source file:edu.ur.hibernate.ir.user.db.HbIrRoleDAO.java

License:Apache License

@SuppressWarnings("unchecked")
public List<IrRole> getRoles(final int rowStart, final int numberOfResultsToShow, final String sortType) {
    List<IrRole> roles = (List<IrRole>) hbCrudDAO.getHibernateTemplate().execute(new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            Query q = null;
            if (sortType.equalsIgnoreCase("asc")) {
                q = session.getNamedQuery("getRolesOrderByNameAsc");
            } else {
                q = session.getNamedQuery("getRolesOrderByNameDesc");
            }/*from  w  w  w  .  ja  va 2 s  .  com*/

            q.setFirstResult(rowStart);
            q.setMaxResults(numberOfResultsToShow);
            q.setReadOnly(true);
            q.setFetchSize(numberOfResultsToShow);
            return q.list();
        }
    });

    return roles;
}

From source file:edu.ur.hibernate.ir.user.db.HbIrUserDAO.java

License:Apache License

/**
 * @see edu.ur.ir.user.IrUserDAO#getUsersPendingAffiliationApprovals(int, int, String)
 *//*w  w w  . j  a  v  a  2  s. c om*/
@SuppressWarnings("unchecked")
public List<IrUser> getUsersPendingAffiliationApprovals(final int rowStart, final int numberOfResultsToShow,
        final String sortType) {
    List<IrUser> users = (List<IrUser>) hbCrudDAO.getHibernateTemplate().execute(new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException, SQLException {

            Query q = null;
            if (sortType.equalsIgnoreCase("asc")) {
                q = session.getNamedQuery("getPendingApprovalsOrderByNameAsc");
            } else {
                q = session.getNamedQuery("getPendingApprovalsOrderByNameDesc");
            }

            q.setFirstResult(rowStart);
            q.setMaxResults(numberOfResultsToShow);
            q.setReadOnly(true);
            q.setFetchSize(numberOfResultsToShow);
            return q.list();
        }
    });

    return users;
}

From source file:edu.ur.hibernate.ir.user.db.HbIrUserGroupDAO.java

License:Apache License

@SuppressWarnings("unchecked")
public List<IrUserGroup> getUserGroups(int rowStart, int numberOfResultsToShow, String sortType) {
    Session session = hbCrudDAO.getSessionFactory().getCurrentSession();
    Query q = null;
    if (sortType.equalsIgnoreCase("asc")) {
        q = session.getNamedQuery("getUserGroupsOrderByNameAsc");
    } else {//w  w  w.j  a  v  a 2 s . c  o m
        q = session.getNamedQuery("getUserGroupsOrderByNameDesc");
    }

    q.setFirstResult(rowStart);
    q.setMaxResults(numberOfResultsToShow);
    q.setReadOnly(true);
    q.setFetchSize(numberOfResultsToShow);
    return q.list();
}

From source file:jedai.domain.security.UsersHome.java

License:Open Source License

/**
 * @param email//from   w  w  w .  j  ava2 s  .com
 * @return
 */
public Users findByEmail(java.lang.String email) {
    log.debug("getting Users instance with email: " + email);
    Session session = sessionFactory.getCurrentSession();

    Users instance = null;

    try {
        session.beginTransaction();

        Query query = session.createQuery("FROM jedai.domain.security.Users WHERE email = :email");
        query.setString("email", email);
        query.setReadOnly(true);

        Object o = query.uniqueResult();
        if (o != null) {
            if (o instanceof Users) {
                instance = (Users) o;
            } else {
                //log.warn("User type was not returned. '{}' was returned", instance
                //      .getClass().getName());
            }
        } else {
            log.info("User was null");
        }

        session.flush();
        session.getTransaction().commit();
        return instance;

    } catch (RuntimeException re) {
        log.error("get failed", re);
        throw re;
    } finally {
        if (session.isOpen()) {
            session.close();
        }
    }
}

From source file:lucee.runtime.orm.hibernate.HibernateORMSession.java

License:Open Source License

private Object __executeQuery(PageContext pc, Session session, Key dsn, String hql, Object params,
        boolean unique, Struct options) throws PageException {
    //Session session = getSession(pc,null);
    hql = hql.trim();//from  w ww .j  a v  a2  s .co  m
    org.hibernate.Query query = session.createQuery(hql);
    // options
    if (options != null) {
        // maxresults
        Object obj = options.get("maxresults", null);
        if (obj != null) {
            int max = CommonUtil.toIntValue(obj, -1);
            if (max < 0)
                throw ExceptionUtil.createException(this, null, "option [maxresults] has an invalid value ["
                        + obj + "], value should be a number bigger or equal to 0", null);
            query.setMaxResults(max);
        }
        // offset
        obj = options.get("offset", null);
        if (obj != null) {
            int off = CommonUtil.toIntValue(obj, -1);
            if (off < 0)
                throw ExceptionUtil.createException(this, null, "option [offset] has an invalid value [" + obj
                        + "], value should be a number bigger or equal to 0", null);
            query.setFirstResult(off);
        }
        // readonly
        obj = options.get("readonly", null);
        if (obj != null) {
            Boolean ro = CommonUtil.toBoolean(obj, null);
            if (ro == null)
                throw ExceptionUtil.createException(this, null,
                        "option [readonly] has an invalid value [" + obj + "], value should be a boolean value",
                        null);
            query.setReadOnly(ro.booleanValue());
        }
        // timeout
        obj = options.get("timeout", null);
        if (obj != null) {
            int to = CommonUtil.toIntValue(obj, -1);
            if (to < 0)
                throw ExceptionUtil.createException(this, null, "option [timeout] has an invalid value [" + obj
                        + "], value should be a number bigger or equal to 0", null);
            query.setTimeout(to);
        }
    }

    // params
    if (params != null) {
        QueryPlanCache cache = data.getQueryPlanCache(dsn);
        HQLQueryPlan plan = cache.getHQLQueryPlan(hql, false, java.util.Collections.EMPTY_MAP);
        ParameterMetadata meta = plan.getParameterMetadata();
        Type type;
        Object obj;

        // struct
        if (CommonUtil.isStruct(params)) {
            Struct sct = CommonUtil.toStruct(params);
            Key[] keys = CommonUtil.keys(sct);
            String name;
            // fix case-senstive
            Struct names = CommonUtil.createStruct();
            if (meta != null) {
                Iterator<String> it = meta.getNamedParameterNames().iterator();
                while (it.hasNext()) {
                    name = it.next();
                    names.setEL(name, name);
                }
            }

            RefBoolean isArray = CommonUtil.createRefBoolean();
            for (int i = 0; i < keys.length; i++) {
                obj = sct.get(keys[i], null);
                if (meta != null) {
                    name = (String) names.get(keys[i], null);
                    if (name == null)
                        continue; // param not needed will be ignored
                    type = meta.getNamedParameterExpectedType(name);
                    obj = HibernateCaster.toSQL(type, obj, isArray);
                    if (isArray.toBooleanValue()) {
                        if (obj instanceof Object[])
                            query.setParameterList(name, (Object[]) obj, type);
                        else if (obj instanceof List)
                            query.setParameterList(name, (List) obj, type);
                        else
                            query.setParameterList(name, Caster.toList(obj), type);
                    } else
                        query.setParameter(name, obj, type);

                } else
                    query.setParameter(keys[i].getString(), obj);
            }
        }

        // array
        else if (CommonUtil.isArray(params)) {
            Array arr = CommonUtil.toArray(params);
            Iterator it = arr.valueIterator();
            int index = 0;
            SQLItem item;
            RefBoolean isArray = null;
            while (it.hasNext()) {
                obj = it.next();
                if (obj instanceof SQLItem) {
                    item = (SQLItem) obj;
                    obj = item.getValue();
                    //HibernateCaster.toHibernateType(item.getType(), null); MUST
                    //query.setParameter(index, item.getValue(),type);
                }
                if (meta != null) {
                    type = meta.getOrdinalParameterExpectedType(index + 1);
                    obj = HibernateCaster.toSQL(type, obj, isArray);
                    // TOOD can the following be done somehow
                    //if(isArray.toBooleanValue())
                    //   query.setParameterList(index, (Object[])obj,type);
                    //else
                    query.setParameter(index, obj, type);
                } else
                    query.setParameter(index, obj);
                index++;
            }
            if (meta.getOrdinalParameterCount() > index)
                throw ExceptionUtil.createException(this, null, "parameter array is to small [" + arr.size()
                        + "], need [" + meta.getOrdinalParameterCount() + "] elements", null);
        }
    }

    // select
    String lcHQL = hql.toLowerCase();
    if (lcHQL.startsWith("select") || lcHQL.startsWith("from")) {
        if (unique) {
            return uniqueResult(query);
        }

        return query.list();
    }
    // update
    return new Double(query.executeUpdate());
}

From source file:org.apache.ode.daohib.bpel.CorrelatorDaoImpl.java

License:Apache License

public boolean checkRoute(CorrelationKeySet correlationKeySet) {
    entering("CorrelatorDaoImpl.checkRoute");
    Query q = getSession().getNamedQuery(HCorrelatorSelector.SELECT_MESSAGE_ROUTE);
    q.setEntity("corr", _hobj);
    q.setString("ckey", correlationKeySet.toCanonicalString());
    q.setReadOnly(true);
    return q.list().isEmpty();
}

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

License:Open Source License

/**
 * Builds the Query object to be used by the getComplianceStatusCounts method.
 * <p></p>/*from ww  w. j  a v a2  s . co m*/
 * The Query object is constructed with HQL translated from the following SQL:
 * <p></p><pre>
 *  SELECT
 *    ConsumerState.uuid,
 *    ComplianceStatusSnap.status,
 *    ComplianceStatusSnap.date
 *
 *  FROM
 *    "gb_consumer_state" ConsumerState
 *
 *    INNER JOIN "gb_consumer_snap" ConsumerSnap
 *      ON ConsumerSnap.uuid = ConsumerState.uuid
 *
 *    INNER JOIN "gb_compliance_snap" ComplianceSnap
 *      ON ComplianceSnap.id = ConsumerSnap.compliance_snap_id
 *
 *    INNER JOIN "gb_compliance_status_snap" ComplianceStatusSnap
 *      ON ComplianceStatusSnap.compliance_snap_id = ComplianceSnap.id
 *
 *  WHERE (
 *      ConsumerState.deleted IS NULL
 *
 *      OR date_part('year', ComplianceSnap.date) < date_part('year', ConsumerState.deleted)
 *
 *      OR (
 *          date_part('year', ComplianceSnap.date) = date_part('year', ConsumerState.deleted)
 *          AND date_part('month', ComplianceSnap.date) < date_part('month', ConsumerState.deleted)
 *      )
 *
 *      OR (
 *          date_part('year', ComplianceSnap.date) = date_part('year', ConsumerState.deleted)
 *          AND date_part('month', ComplianceSnap.date) = date_part('month', ConsumerState.deleted)
 *          AND date_part('day', ComplianceSnap.date) < date_part('day', ConsumerState.deleted)
 *      )
 *    )
 *
 *    AND (ComplianceStatusSnap.date, ConsumerSnap.uuid) IN (
 *      SELECT
 *        max(ComplianceSnap2.date) AS maxdate,
 *        ConsumerState2.uuid
 *
 *      FROM
 *        "gb_consumer_state" ConsumerState2
 *
 *        INNER JOIN "gb_consumer_snap" ConsumerSnap2
 *          ON ConsumerSnap2.uuid = ConsumerState2.uuid
 *
 *        INNER JOIN "gb_compliance_snap" ComplianceSnap2
 *          ON ComplianceSnap2.id = ConsumerSnap2.compliance_snap_id
 *
 *        INNER JOIN "gb_compliance_status_snap" ComplianceStatusSnap2
 *          ON ComplianceStatusSnap2.compliance_snap_id = ComplianceSnap2.id
 *
 *      GROUP BY
 *        date_part('year', ComplianceSnap2.date),
 *        date_part('month', ComplianceSnap2.date),
 *        date_part('day', ComplianceSnap2.date),
 *        ConsumerState2.uuid
 *    )
 *
 *    -- Min date
 *    AND (
 *      date_part('year', ComplianceSnap.date) > 2014
 *
 *      OR (
 *        date_part('year', ComplianceSnap.date) = 2014
 *        AND date_part('month', ComplianceSnap.date) > 11
 *      )
 *
 *      OR (
 *        date_part('year', ComplianceSnap.date) = 2014
 *        AND date_part('month', ComplianceSnap.date) = 11
 *        AND date_part('day', ComplianceSnap.date) >= 25
 *      )
 *
 *      OR (ComplianceStatusSnap.date, ConsumerSnap.uuid) IN (
 *        SELECT
 *          max(ComplianceSnap3.date) AS maxdate,
 *          ConsumerState3.uuid
 *
 *        FROM
 *          "gb_consumer_state" ConsumerState3
 *
 *          INNER JOIN "gb_consumer_snap" ConsumerSnap3
 *            ON ConsumerSnap3.uuid = ConsumerState3.uuid
 *
 *          INNER JOIN "gb_compliance_snap" ComplianceSnap3
 *            ON ComplianceSnap3.id = ConsumerSnap3.compliance_snap_id
 *
 *          INNER JOIN "gb_compliance_status_snap" ComplianceStatusSnap3
 *            ON ComplianceStatusSnap3.compliance_snap_id = ComplianceSnap3.id
 *
 *        WHERE
 *          date_part('year', ComplianceSnap3.date) < 2014
 *
 *          OR (
 *            date_part('year', ComplianceSnap3.date) = 2014
 *            AND date_part('month', ComplianceSnap3.date) < 11
 *          )
 *
 *          OR (
 *            date_part('year', ComplianceSnap3.date) = 2014
 *            AND date_part('month', ComplianceSnap3.date) = 11
 *            AND date_part('day', ComplianceSnap3.date) < 25
 *          )
 *
 *        GROUP BY
 *          ConsumerState3.uuid
 *      )
 *    )
 *
 *    -- Max date
 *    AND (
 *      date_part('year', ComplianceSnap.date) < 2014
 *
 *      OR (
 *        date_part('year', ComplianceSnap.date) = 2014
 *        AND date_part('month', ComplianceSnap.date) < 11
 *      )
 *
 *      OR (
 *        date_part('year', ComplianceSnap.date) = 2014
 *        AND date_part('month', ComplianceSnap.date) = 11
 *        AND date_part('day', ComplianceSnap.date) <= 15
 *      )
 *    )
 *
 *    -- Checking for the SKU, Product Name or attributes
 *    AND ComplianceSnap.id IN (
 *      SELECT ConsumerSnapI.compliance_snap_id
 *        FROM "gb_consumer_snap" ConsumerSnapI
 *        LEFT JOIN "gb_entitlement_snap" EntitlementSnap
 *          ON EntitlementSnap.compliance_snap_id = ConsumerSnapI.compliance_snap_id
 *
 *        LEFT JOIN "gb_ent_attr_snap" EntitlementAttributeSnap
 *          ON EntitlementAttributeSnap.ent_snap_id = EntitlementSnap.id
 *
 *        WHERE
 *          ConsumerSnapI.uuid = ConsumerSnap.uuid
 *          --AND (
 *          --  EntitlementSnap.product_id = User-input SKU
 *          --  OR EntitlementSnap.product_name = User-input name (matches-like?)
 *          --  OR (
 *          --    EntitlementAttributeSnap.gb_ent_attr_name = 'management_enabled'
 *          --    AND EntitlementAttributeSnap.gb_ent_attr_value = 1
 *          --  )
 *          --)
 *    )
 *
 *  ORDER BY
 *    ComplianceStatusSnap.date ASC
 *  </pre>
 *
 * @param session
 *  The session to use to create the query.
 *
 * @param startDate
 *  The date at which the time span should begin. If null, all compliance statuses before the
 *  end date (if provided) will be used.
 *
 * @param endDate
 *  The date at which the time span should end. If null, all compliance statuses after the
 *  start date (if provided) will be used.
 *
 * @param sku
 *  A subscription sku to use to filter compliance status counts. If provided, only consumers
 *  using the specified sku will be counted.
 *
 * @param subscriptionName
 *  A product name to use to filter compliance status counts. If provided, only consumers using
 *  subscriptions which provide the specified product name will be counted.
 *
 * @param productName
 *  A product name to use to filter compliance status counts. If provided, only consumers with
 *  an installed product with the specified product name will be counted.
 *
 * @param attributes
 *  A map of entitlement attributes to use to filter compliance status counts. If provided, only
 *  consumers with entitlements having the specified values for the given attributes will be
 *  counted.
 *
 * @param ownerKey
 *  An owner key to use to filter compliance status counts. If provided, only consumers
 *  associated with the specified owner key/account will be counted.
 *
 * @return
 *  A Query object to be used for retrieving compliance status counts.
 */
@SuppressWarnings({ "checkstyle:methodlength", "checkstyle:indentation" })
private Query buildComplianceStatusCountQuery(Session session, Date startDate, Date endDate, String ownerKey,
        List<String> consumerUuids, String sku, String subscriptionName, String productName,
        Map<String, String> attributes) {

    List<Object> parameters = new LinkedList<Object>();
    int counter = 0;

    StringBuilder hql = new StringBuilder("SELECT " + "ConsumerState.uuid," + "ComplianceStatusSnap.status,"
            + "ComplianceStatusSnap.date," + "ConsumerState.deleted " +

            "FROM " + "Consumer AS ConsumerSnap " + "INNER JOIN ConsumerSnap.consumerState AS ConsumerState "
            + "INNER JOIN ConsumerSnap.complianceSnapshot AS ComplianceSnap "
            + "INNER JOIN ComplianceSnap.status AS ComplianceStatusSnap "
            + "LEFT JOIN ComplianceSnap.entitlements AS EntitlementSnap " +

            "WHERE (" + "ConsumerState.deleted IS NULL "
            + "OR year(ComplianceSnap.date) < year(ConsumerState.deleted) " + "OR ("
            + "year(ComplianceSnap.date) = year(ConsumerState.deleted) "
            + "AND month(ComplianceSnap.date) < month(ConsumerState.deleted) " + ") " + "OR ("
            + "year(ComplianceSnap.date) = year(ConsumerState.deleted) "
            + "AND month(ComplianceSnap.date) = month(ConsumerState.deleted) "
            + "AND day(ComplianceSnap.date) < day(ConsumerState.deleted)" + ")" + ") " +

            "AND (ComplianceStatusSnap.date, ConsumerSnap.uuid) IN (" + "SELECT "
            + "max(ComplianceSnap2.date) AS maxdate, " + "ConsumerState2.uuid " +

            "FROM " + "Consumer AS ConsumerSnap2 " + "INNER JOIN ConsumerSnap2.consumerState AS ConsumerState2 "
            + "INNER JOIN ConsumerSnap2.complianceSnapshot AS ComplianceSnap2 "
            + "INNER JOIN ComplianceSnap2.status AS ComplianceStatusSnap2 " +

            "GROUP BY " + "year(ComplianceSnap2.date)," + "month(ComplianceSnap2.date),"
            + "day(ComplianceSnap2.date)," + "ConsumerState2.uuid " + ") ");

    // Add our reporting criteria...
    if (sku != null || subscriptionName != null || (attributes != null && attributes.size() > 0)
            || ownerKey != null || (consumerUuids != null && consumerUuids.size() > 0) || productName != null) {

        List<String> criteria = new LinkedList<String>();
        StringBuffer inner = new StringBuffer("AND (");

        // TODO:
        // Owner, SKU, product name and should be replaced by the same mechanism we used for
        // --matches in Subscription-manager.
        if (ownerKey != null) {
            criteria.add("ConsumerState.ownerKey = ?" + ++counter);
            parameters.add(ownerKey);
        }

        if (sku != null) {
            criteria.add("EntitlementSnap.productId = ?" + ++counter);
            parameters.add(sku);
        }

        if (subscriptionName != null) {
            criteria.add("EntitlementSnap.productName = ?" + ++counter);
            parameters.add(subscriptionName);
        }

        if (productName != null) {
            criteria.add(String.format("?%d IN (" + "SELECT Installed.productName " + "FROM "
                    + "Consumer AS ConsumerSnapP " + "INNER JOIN ConsumerSnapP.installedProducts AS Installed "
                    + "INNER JOIN ConsumerSnapP.complianceSnapshot AS ComplianceSnapP "
                    + "INNER JOIN ComplianceSnapP.status AS ComplianceStatusSnapP "
                    + "LEFT JOIN ComplianceStatusSnapP.compliantProducts AS CProduct "
                    + "LEFT JOIN ComplianceStatusSnapP.nonCompliantProducts AS NCProduct "
                    + "LEFT JOIN ComplianceStatusSnapP.partiallyCompliantProducts AS PCProduct " + "WHERE "
                    + "ComplianceStatusSnapP.id = ComplianceStatusSnap.id " + "AND ("
                    + "Installed.productId = CProduct.productId "
                    + "OR Installed.productId = NCProduct.productId "
                    + "OR Installed.productId = PCProduct.productId " + ")" + ")", ++counter));

            parameters.add(productName);
        }

        if (attributes != null && attributes.size() > 0) {
            if (attributes.containsKey("management_enabled")) {
                boolean managementEnabledFilter = PropertyConverter
                        .toBoolean(attributes.get("management_enabled"));
                criteria.add("ComplianceStatusSnap.managementEnabled = ?" + ++counter);
                parameters.add(managementEnabledFilter);

                // Don't process this attribute as part of entitlement attributes,
                // as it has already been handled.
                attributes.remove("management_enabled");
            }

            for (Map.Entry<String, String> entry : attributes.entrySet()) {
                criteria.add(String.format(
                        "(?%d, ?%d) IN (" + "SELECT ENTRY(EntitlementSnapA.attributes) "
                                + "FROM Entitlement AS EntitlementSnapA "
                                + "WHERE EntitlementSnapA.id = EntitlementSnap.id" + ")",
                        ++counter, ++counter));

                parameters.add(entry.getKey());
                parameters.add(entry.getValue());
            }
        }

        if (consumerUuids != null && consumerUuids.size() > 0) {
            criteria.add("ConsumerState.uuid IN (?" + ++counter + ")");
            parameters.add(consumerUuids);
        }

        // Append the criteria to our where clause and close it.
        Iterator<String> ci = criteria.iterator();
        inner.append(ci.next());

        while (ci.hasNext()) {
            inner.append(" AND ");
            inner.append(ci.next());
        }

        hql.append(inner.append(") "));
    }

    // Add our date range, if necessary...
    if (startDate != null) {
        int year = startDate.getYear() + 1900;
        int month = startDate.getMonth() + 1;
        int day = startDate.getDate();

        hql.append(String.format("AND (" + "year(ComplianceStatusSnap.date) > ?%1$d " + "OR ("
                + "year(ComplianceStatusSnap.date) = ?%1$d " + "AND month(ComplianceStatusSnap.date) > ?%2$d"
                + ") " + "OR (" + "year(ComplianceStatusSnap.date) = ?%1$d "
                + " AND month(ComplianceStatusSnap.date) = ?%2$d "
                + " AND day(ComplianceStatusSnap.date) >= ?%3$d" + ") "
                + "OR (ComplianceStatusSnap.date, ConsumerSnap.uuid) IN (" + "SELECT "
                + "max(ComplianceStatusSnap2.date) AS maxdate, " + "ConsumerState2.uuid " +

                "FROM " + "Consumer AS ConsumerSnap2 "
                + "INNER JOIN ConsumerSnap2.consumerState AS ConsumerState2 "
                + "INNER JOIN ConsumerSnap2.complianceSnapshot AS ComplianceSnap2 "
                + "INNER JOIN ComplianceSnap2.status AS ComplianceStatusSnap2 " +

                "WHERE " + "year(ComplianceStatusSnap2.date) < ?%1$d " + "OR ("
                + "year(ComplianceStatusSnap2.date) = ?%1$d " + "AND month(ComplianceStatusSnap2.date) < ?%2$d"
                + ") " + "OR (" + "year(ComplianceStatusSnap2.date) = ?%1$d "
                + "AND month(ComplianceStatusSnap2.date) = ?%2$d "
                + "AND day(ComplianceStatusSnap2.date) < ?%3$d" + ") " +

                "GROUP BY " + "ConsumerState2.uuid" + ")" + ") ", ++counter, ++counter, ++counter));

        parameters.add(year);
        parameters.add(month);
        parameters.add(day);
    }

    if (endDate != null) {
        int year = endDate.getYear() + 1900;
        int month = endDate.getMonth() + 1;
        int day = endDate.getDate();

        hql.append(String.format("AND (" + "year(ComplianceStatusSnap.date) < ?%1$d " + "OR ("
                + "year(ComplianceStatusSnap.date) = ?%1$d " + "AND month(ComplianceStatusSnap.date) < ?%2$d "
                + ") " + "OR (" + "year(ComplianceStatusSnap.date) = ?%1$d "
                + "AND month(ComplianceStatusSnap.date) = ?%2$d "
                + "AND day(ComplianceStatusSnap.date) <= ?%3$d" + ")" + ") ", ++counter, ++counter, ++counter));

        parameters.add(year);
        parameters.add(month);
        parameters.add(day);
    }

    // Add our grouping...
    hql.append("ORDER BY ComplianceStatusSnap.date ASC");

    // log.debug("\nFINAL QUERY: {}", hql.toString());

    // Build our query object and set the parameters...
    Query query = session.createQuery(hql.toString());
    query.setReadOnly(true);

    for (int i = 1; i <= counter; ++i) {
        Object param = parameters.remove(0);

        if (param instanceof Collection) {
            query.setParameterList(String.valueOf(i), (Collection) param);
        } else {
            query.setParameter(String.valueOf(i), param);
        }
    }

    return query;
}

From source file:org.codehaus.groovy.grails.orm.hibernate.metaclass.ExecuteQueryPersistentMethod.java

License:Apache License

@SuppressWarnings("rawtypes")
@Override/*  w  w  w.  j  a va  2 s .  c o m*/
protected Object doInvokeInternal(Class clazz, String methodName, Closure additionalCriteria,
        Object[] arguments) {
    checkMethodSignature(clazz, arguments);

    final String query = arguments[0].toString();
    final Map queryMetaParams = extractQueryMetaParams(arguments);
    final List positionalParams = extractPositionalParams(arguments);
    final Map namedParams = extractNamedParams(arguments);

    return getHibernateTemplate().executeFind(new HibernateCallback<Object>() {
        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            Query q = session.createQuery(query);
            SimpleTypeConverter converter = new SimpleTypeConverter();
            // process paginate params
            if (queryMetaParams.containsKey(GrailsHibernateUtil.ARGUMENT_MAX)) {
                Integer maxParam = converter.convertIfNecessary(
                        queryMetaParams.get(GrailsHibernateUtil.ARGUMENT_MAX), Integer.class);
                q.setMaxResults(maxParam.intValue());
            }
            if (queryMetaParams.containsKey(GrailsHibernateUtil.ARGUMENT_OFFSET)) {
                Integer offsetParam = converter.convertIfNecessary(
                        queryMetaParams.get(GrailsHibernateUtil.ARGUMENT_OFFSET), Integer.class);
                q.setFirstResult(offsetParam.intValue());
            }
            if (queryMetaParams.containsKey(GrailsHibernateUtil.ARGUMENT_CACHE)) {
                q.setCacheable(
                        ((Boolean) queryMetaParams.get(GrailsHibernateUtil.ARGUMENT_CACHE)).booleanValue());
            }
            if (queryMetaParams.containsKey(GrailsHibernateUtil.ARGUMENT_FETCH_SIZE)) {
                Integer fetchSizeParam = converter.convertIfNecessary(
                        queryMetaParams.get(GrailsHibernateUtil.ARGUMENT_FETCH_SIZE), Integer.class);
                q.setFetchSize(fetchSizeParam.intValue());
            }
            if (queryMetaParams.containsKey(GrailsHibernateUtil.ARGUMENT_TIMEOUT)) {
                Integer timeoutParam = converter.convertIfNecessary(
                        queryMetaParams.get(GrailsHibernateUtil.ARGUMENT_TIMEOUT), Integer.class);
                q.setFetchSize(timeoutParam.intValue());
            }
            if (queryMetaParams.containsKey(GrailsHibernateUtil.ARGUMENT_READ_ONLY)) {
                q.setReadOnly(
                        ((Boolean) queryMetaParams.get(GrailsHibernateUtil.ARGUMENT_READ_ONLY)).booleanValue());
            }
            if (queryMetaParams.containsKey(GrailsHibernateUtil.ARGUMENT_FLUSH_MODE)) {
                q.setFlushMode((FlushMode) queryMetaParams.get(GrailsHibernateUtil.ARGUMENT_FLUSH_MODE));
            }
            // process positional HQL params
            int index = 0;
            for (Object parameter : positionalParams) {
                q.setParameter(index++, parameter instanceof CharSequence ? parameter.toString() : parameter);
            }

            // process named HQL params
            for (Object o : namedParams.entrySet()) {
                Map.Entry entry = (Map.Entry) o;
                if (!(entry.getKey() instanceof String)) {
                    throw new GrailsQueryException("Named parameter's name must be of type String");
                }
                String parameterName = (String) entry.getKey();
                if (!QUERY_META_PARAMS.contains(parameterName)) {
                    Object parameterValue = entry.getValue();
                    if (parameterValue == null) {
                        throw new IllegalArgumentException(
                                "Named parameter [" + entry.getKey() + "] value may not be null");
                    }
                    if (Collection.class.isAssignableFrom(parameterValue.getClass())) {
                        q.setParameterList(parameterName, (Collection) parameterValue);
                    } else if (parameterValue.getClass().isArray()) {
                        q.setParameterList(parameterName, (Object[]) parameterValue);
                    } else if (parameterValue instanceof CharSequence) {
                        q.setParameter(parameterName, parameterValue.toString());
                    } else {
                        q.setParameter(parameterName, parameterValue);
                    }
                }
            }
            return q.list();
        }
    });
}

From source file:org.easybatch.extensions.hibernate.HibernateRecordReader.java

License:Open Source License

@Override
public void open() {
    currentRecordNumber = 0;//from w  w  w  .j a  v a  2  s.com
    Query hibernateQuery = session.createQuery(query);
    hibernateQuery.setReadOnly(true);
    if (maxResults >= 1) {
        hibernateQuery.setMaxResults(maxResults);
    }
    if (fetchSize >= 1) {
        hibernateQuery.setFetchSize(fetchSize);
    }
    scrollableResults = hibernateQuery.scroll(ScrollMode.FORWARD_ONLY);
}