Example usage for org.hibernate Query setCacheable

List of usage examples for org.hibernate Query setCacheable

Introduction

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

Prototype

Query<R> setCacheable(boolean cacheable);

Source Link

Document

Enable/disable second level query (result) caching for this query.

Usage

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

License:Apache License

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override//from   w  w w  .jav a  2 s .co  m
protected Object doInvokeInternal(final Class clazz, String methodName, Closure additionalCriteria,
        final Object[] arguments) {

    if (arguments.length == 0) {
        throw new MissingMethodException(methodName, clazz, arguments);
    }

    final Object arg = arguments[0] instanceof CharSequence ? arguments[0].toString() : arguments[0];

    if (arg instanceof String) {
        final String query = (String) arg;
        final String shortName = GrailsNameUtils.getShortName(clazz);
        if (!query.matches("from [" + clazz.getName() + "|" + shortName + "].*")) {
            throw new GrailsQueryException("Invalid query [" + query + "] for domain class [" + clazz + "]");
        }

        return getHibernateTemplate().execute(new HibernateCallback<Object>() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                Query q = session.createQuery(query);
                Object[] queryArgs = null;
                Map queryNamedArgs = null;
                boolean useCache = useCache(arguments);

                if (arguments.length > 1) {
                    if (arguments[1] instanceof Collection) {
                        queryArgs = GrailsClassUtils.collectionToObjectArray((Collection) arguments[1]);
                    } else if (arguments[1].getClass().isArray()) {
                        queryArgs = (Object[]) arguments[1];
                    } else if (arguments[1] instanceof Map) {
                        queryNamedArgs = (Map) arguments[1];
                    }
                }
                if (queryArgs != null) {
                    for (int i = 0; i < queryArgs.length; i++) {
                        if (queryArgs[i] instanceof CharSequence) {
                            q.setParameter(i, queryArgs[i].toString());
                        } else {
                            q.setParameter(i, queryArgs[i]);
                        }
                    }
                }
                if (queryNamedArgs != null) {
                    for (Iterator it = queryNamedArgs.entrySet().iterator(); it.hasNext();) {
                        Map.Entry entry = (Map.Entry) it.next();
                        if (!(entry.getKey() instanceof String)) {
                            throw new GrailsQueryException(
                                    "Named parameter's name must be String: " + queryNamedArgs.toString());
                        }
                        String stringKey = (String) entry.getKey();
                        Object value = entry.getValue();

                        if (GrailsHibernateUtil.ARGUMENT_CACHE.equals(stringKey)) {
                            continue;
                        } else if (value instanceof CharSequence) {
                            q.setParameter(stringKey, value.toString());
                        } else if (List.class.isAssignableFrom(value.getClass())) {
                            q.setParameterList(stringKey, (List) value);
                        } else if (value.getClass().isArray()) {
                            q.setParameterList(stringKey, (Object[]) value);
                        } else {
                            q.setParameter(stringKey, value);
                        }
                    }
                }
                // only want one result, could have used uniqueObject here
                // but it throws an exception if its not unique which is undesirable
                q.setMaxResults(1);
                q.setCacheable(useCache);
                List results = q.list();
                if (results.size() > 0) {
                    return GrailsHibernateUtil.unwrapIfProxy(results.get(0));
                }
                return null;
            }

            private boolean useCache(Object[] args) {
                boolean useCache = false;
                if (args.length > 1 && args[args.length - 1] instanceof Map) {
                    Object param = args[args.length - 1];
                    String key = GrailsHibernateUtil.ARGUMENT_CACHE;
                    boolean value = false;
                    if ((param instanceof Map) && ((Map) param).containsKey(key)) {
                        SimpleTypeConverter converter = new SimpleTypeConverter();
                        value = converter.convertIfNecessary(((Map) param).get(key), Boolean.class);
                    }
                    useCache = value;
                }
                return useCache;
            }
        });
    } else if (clazz.isAssignableFrom(arg.getClass())) {
        // if the arg is an instance of the class find by example
        return getHibernateTemplate().execute(new HibernateCallback<Object>() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {

                Example example = Example.create(arg).ignoreCase();

                Criteria crit = session.createCriteria(clazz);
                crit.add(example);
                crit.setMaxResults(1);
                List results = crit.list();
                if (results.size() > 0) {
                    return results.get(0);
                }
                return null;
            }
        });
    }

    throw new MissingMethodException(methodName, clazz, arguments);
}

From source file:org.devproof.portal.core.module.common.repository.DataProviderRepositoryImpl.java

License:Apache License

private void handleCacheConfiguration(Query q, CacheQuery cacheAnnotation) {
    q.setCacheable(cacheAnnotation.enabled());
    if (!"".equals(cacheAnnotation.region())) {
        q.setCacheMode(CacheMode.parse(cacheAnnotation.cacheMode()));
    }/*from  ww w  .  j  a va  2 s.  c o m*/
    if (!"".equals(cacheAnnotation.region())) {
        q.setCacheRegion(cacheAnnotation.region());
    }
}

From source file:org.dspace.eperson.dao.impl.GroupDAOImpl.java

License:BSD License

@Override
public List<Group> findAll(Context context) throws SQLException {
    Query query = createQuery(context, "SELECT g FROM Group g ORDER BY g.name ASC");
    query.setCacheable(true);

    return list(query);
}

From source file:org.dspace.eperson.dao.impl.GroupDAOImpl.java

License:BSD License

@Override
public List<Group> findByEPerson(Context context, EPerson ePerson) throws SQLException {
    Query query = createQuery(context,
            "from Group where (from EPerson e where e.id = :eperson_id) in elements(epeople)");
    query.setParameter("eperson_id", ePerson.getID());
    query.setCacheable(true);

    return list(query);
}

From source file:org.dspace.eperson.dao.impl.GroupDAOImpl.java

License:BSD License

@Override
public Group findByName(final Context context, final String name) throws SQLException {
    Query query = createQuery(context, "SELECT g from Group g " + "where g.name = :name ");

    query.setParameter("name", name);
    query.setCacheable(true);

    return uniqueResult(query);
}

From source file:org.dspace.eperson.dao.impl.GroupDAOImpl.java

License:BSD License

@Override
public Group findByNameAndEPerson(Context context, String groupName, EPerson ePerson) throws SQLException {
    if (groupName == null || ePerson == null) {
        return null;
    } else {//ww  w  .ja v a  2  s  .co m
        Query query = createQuery(context,
                "SELECT DISTINCT g FROM Group g " + "LEFT JOIN g.epeople p " + "WHERE g.name = :name AND "
                        + "(p.id = :eperson_id OR " + "EXISTS ( " + "SELECT 1 FROM Group2GroupCache gc "
                        + "JOIN gc.parent p " + "JOIN gc.child c " + "JOIN c.epeople cp "
                        + "WHERE p.id = g.id AND cp.id = :eperson_id " + ") " + ")");

        query.setParameter("name", groupName);
        query.setParameter("eperson_id", ePerson.getID());
        query.setCacheable(true);

        return uniqueResult(query);
    }
}

From source file:org.eclipse.emf.teneo.hibernate.HbSessionWrapper.java

License:Open Source License

/** Query */
public List<?> executeQuery(String qry, boolean cacheable) {
    final Query query = getSessionInternal().createQuery(qry);
    query.setCacheable(cacheable);
    return query.list();
}

From source file:org.efs.openreports.providers.HibernateProvider.java

License:Open Source License

public List<?> query(String fromClause) throws ProviderException {
    Session session = openSession();// ww w .  jav a 2 s .  c  o  m

    try {
        Query query = session.createQuery(fromClause);
        query.setCacheable(true);

        List<?> list = query.list();

        return list;
    } catch (HibernateException he) {
        throw new ProviderException(he);
    } finally {
        closeSession(session);
    }
}

From source file:org.efs.openreports.providers.impl.TagProviderImpl.java

License:Open Source License

public String getTagList(Class objectClass, String tagType) throws ProviderException {
    StringBuffer queryString = new StringBuffer();
    queryString.append("select distinct orTag.tag from org.efs.openreports.objects.ORTag orTag ");
    queryString.append("where orTag.tagType = ? ");
    if (objectClass != null)
        queryString.append("and orTag.objectClass = ? ");
    queryString.append("order by orTag.tag ");

    Session session = hibernateProvider.openSession();

    try {/*from   www .j  a  v a2 s. co  m*/
        Query query = session.createQuery(queryString.toString());
        query.setCacheable(true);
        query.setString(0, tagType);

        if (objectClass != null)
            query.setString(1, objectClass.getName());

        return formatTags(query.list());
    } catch (HibernateException he) {
        throw new ProviderException(he);
    } finally {
        hibernateProvider.closeSession(session);
    }
}

From source file:org.egov.billsaccounting.services.CreateVoucher.java

License:Open Source License

public void validateTransaction(final List<HashMap<String, Object>> accountcodedetails,
        final List<HashMap<String, Object>> subledgerdetails) throws ApplicationRuntimeException, Exception {
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("START | validateTransaction");
    // List<Transaxtion> transaxtionList = new ArrayList<Transaxtion>();
    BigDecimal totaldebitAmount = BigDecimal.valueOf(0);
    BigDecimal totalcreditAmount = BigDecimal.valueOf(0);
    final Map<String, BigDecimal> accDetAmtMap = new HashMap<String, BigDecimal>();
    for (final HashMap<String, Object> accDetailMap : accountcodedetails) {

        String glcode = null;// www  .  j  av a2s.c o m

        final BigDecimal debitAmount = new BigDecimal(accDetailMap.get(VoucherConstant.DEBITAMOUNT).toString());
        final BigDecimal creditAmount = new BigDecimal(
                accDetailMap.get(VoucherConstant.CREDITAMOUNT).toString());

        totaldebitAmount = totaldebitAmount.add(debitAmount);
        totalcreditAmount = totalcreditAmount.add(creditAmount);
        if (accDetailMap.containsKey(VoucherConstant.GLCODE)
                && null != accDetailMap.get(VoucherConstant.GLCODE)) {
            glcode = accDetailMap.get(VoucherConstant.GLCODE).toString();
            if (null == chartOfAccountsDAO.getCChartOfAccountsByGlCode(glcode))
                throw new ApplicationRuntimeException("Not a valid account code" + glcode);
        } else
            throw new ApplicationRuntimeException("glcode is missing or null");
        if (debitAmount.compareTo(BigDecimal.ZERO) != 0 && creditAmount.compareTo(BigDecimal.ZERO) != 0)
            throw new ApplicationRuntimeException(
                    "Both debit amount and credit amount cannot be greater than zero");
        if (debitAmount.compareTo(BigDecimal.ZERO) == 0 && creditAmount.compareTo(BigDecimal.ZERO) == 0)
            throw new ApplicationRuntimeException("debit and credit both amount is Zero");
        if (null != accDetailMap.get(VoucherConstant.FUNCTIONCODE)
                && "" != accDetailMap.get(VoucherConstant.FUNCTIONCODE)) {
            final String functionCode = accDetailMap.get(VoucherConstant.FUNCTIONCODE).toString();
            if (null == functionDAO.getFunctionByCode(functionCode))
                throw new ApplicationRuntimeException("not a valid function code");
        }
        if (debitAmount.compareTo(BigDecimal.ZERO) != 0) {
            if (null != accDetAmtMap.get(VoucherConstant.DEBIT + glcode)) {
                final BigDecimal accountCodeTotDbAmt = accDetAmtMap.get(VoucherConstant.DEBIT + glcode)
                        .add(debitAmount);
                accDetAmtMap.put(VoucherConstant.DEBIT + glcode, accountCodeTotDbAmt);
            } else
                accDetAmtMap.put(VoucherConstant.DEBIT + glcode, debitAmount);

        } else if (creditAmount.compareTo(BigDecimal.ZERO) != 0)
            if (null != accDetAmtMap.get(VoucherConstant.CREDIT + glcode)) {
                final BigDecimal accountCodeTotCrAmt = accDetAmtMap.get(VoucherConstant.CREDIT + glcode)
                        .add(creditAmount);
                accDetAmtMap.put(VoucherConstant.CREDIT + glcode, accountCodeTotCrAmt);
            } else
                accDetAmtMap.put(VoucherConstant.CREDIT + glcode, creditAmount);
    }
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Total Debit  amount   :" + totaldebitAmount);
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Total Credit amount   :" + totalcreditAmount);
    totaldebitAmount = totaldebitAmount.setScale(2, BigDecimal.ROUND_HALF_UP);
    totalcreditAmount = totalcreditAmount.setScale(2, BigDecimal.ROUND_HALF_UP);
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Total Debit  amount after round off :" + totaldebitAmount);
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Total Credit amount after round off :" + totalcreditAmount);
    if (totaldebitAmount.compareTo(totalcreditAmount) != 0)
        throw new ApplicationRuntimeException("total debit and total credit amount is not matching");
    final Map<String, BigDecimal> subledAmtmap = new HashMap<String, BigDecimal>();
    for (final HashMap<String, Object> subdetailDetailMap : subledgerdetails) {
        String glcode = null;
        String detailtypeid = null;
        String detailKeyId = null;
        if (null != subdetailDetailMap.get(VoucherConstant.GLCODE)) {
            glcode = subdetailDetailMap.get(VoucherConstant.GLCODE).toString();
            if (null == chartOfAccountsDAO.getCChartOfAccountsByGlCode(glcode))
                throw new ApplicationRuntimeException("not a valid glcode");
        } else
            throw new ApplicationRuntimeException("glcode is missing");
        final Query querytds = persistenceService.getSession()
                .createQuery("select t.id from Recovery t where " + "t.chartofaccounts.glcode=:glcode");
        querytds.setString("glcode", glcode);
        querytds.setCacheable(true);
        if (null != querytds.list() && querytds.list().size() > 0
                && null == subdetailDetailMap.get(VoucherConstant.TDSID)
                && null != subdetailDetailMap.get(VoucherConstant.CREDITAMOUNT)
                && new BigDecimal(subdetailDetailMap.get(VoucherConstant.CREDITAMOUNT).toString())
                        .compareTo(BigDecimal.ZERO) != 0) {
            /*
             * Commenting out throw ApplicationRuntimeException since we are
             * using the same API for create Journal Voucher. There we are
             * not setting the TDS id..
             */
            // throw new
            // ApplicationRuntimeException("Recovery detail is missing for glcode :"+glcode);
        }
        // validate the glcode is a subledger code or not.

        final Query query = persistenceService.getSession()
                .createQuery("from CChartOfAccountDetail cd,CChartOfAccounts c where "
                        + "cd.glCodeId = c.id and c.glcode=:glcode");

        query.setString(VoucherConstant.GLCODE, glcode);
        query.setCacheable(true);
        if (null == query.list() || query.list().size() == 0)
            throw new ApplicationRuntimeException("This code is not a control code" + glcode);

        // validate subledger Detailtypeid

        if (null != subdetailDetailMap.get(VoucherConstant.DETAILTYPEID)) {
            detailtypeid = subdetailDetailMap.get(VoucherConstant.DETAILTYPEID).toString();
            final Session session = persistenceService.getSession();
            final Query qry = session.createQuery("from CChartOfAccountDetail cd,CChartOfAccounts c where "
                    + "cd.glCodeId = c.id and c.glcode=:glcode and cd.detailTypeId.id=:detailTypeId");
            qry.setString(VoucherConstant.GLCODE, glcode);
            qry.setInteger("detailTypeId", Integer.valueOf(detailtypeid));
            qry.setCacheable(true);
            if (null == qry.list() || qry.list().size() == 0)
                throw new ApplicationRuntimeException(
                        "The subledger type mapped to this account code is not correct " + glcode);
        } else
            throw new ApplicationRuntimeException("Subledger type value is missing for account code " + glcode);

        if (null != subdetailDetailMap.get(VoucherConstant.DETAILKEYID)) {
            detailKeyId = subdetailDetailMap.get(VoucherConstant.DETAILKEYID).toString();
            final Session session = persistenceService.getSession();
            final Query qry = session.createQuery(
                    "from Accountdetailkey adk where adk.accountdetailtype.id=:detailtypeid and adk.detailkey=:detailkey");
            qry.setInteger(VoucherConstant.DETAILTYPEID, Integer.valueOf(detailtypeid));
            qry.setInteger("detailkey", Integer.valueOf(detailKeyId));
            qry.setCacheable(true);
            if (null == qry.list() || qry.list().size() == 0)
                throw new ApplicationRuntimeException("Subledger data is not valid for account code " + glcode);
        } else
            throw new ApplicationRuntimeException("detailkeyid is missing");

        if (null != subdetailDetailMap.get(VoucherConstant.DEBITAMOUNT)
                && new BigDecimal(subdetailDetailMap.get(VoucherConstant.DEBITAMOUNT).toString())
                        .compareTo(BigDecimal.ZERO) != 0) {
            final BigDecimal dbtAmount = new BigDecimal(
                    subdetailDetailMap.get(VoucherConstant.DEBITAMOUNT).toString());
            if (null != subledAmtmap.get(VoucherConstant.DEBIT + glcode))
                subledAmtmap.put(VoucherConstant.DEBIT + glcode,
                        subledAmtmap.get(VoucherConstant.DEBIT + glcode).add(dbtAmount));
            else
                subledAmtmap.put(VoucherConstant.DEBIT + glcode, dbtAmount);

        } else if (null != subdetailDetailMap.get(VoucherConstant.CREDITAMOUNT)
                && new BigDecimal(subdetailDetailMap.get(VoucherConstant.CREDITAMOUNT).toString())
                        .compareTo(BigDecimal.ZERO) != 0) {
            final BigDecimal creditAmt = new BigDecimal(
                    subdetailDetailMap.get(VoucherConstant.CREDITAMOUNT).toString());
            if (null != subledAmtmap.get(VoucherConstant.CREDIT + glcode))
                subledAmtmap.put(VoucherConstant.CREDIT + glcode,
                        subledAmtmap.get(VoucherConstant.CREDIT + glcode).add(creditAmt));
            else
                subledAmtmap.put(VoucherConstant.CREDIT + glcode, creditAmt);

        } else
            throw new ApplicationRuntimeException(
                    "Incorrect Sub ledger amount supplied for glcode : " + glcode);

    }

    for (final HashMap<String, Object> accDetailMap : accountcodedetails) {

        final String glcode = accDetailMap.get(VoucherConstant.GLCODE).toString();

        if (null != subledAmtmap.get(VoucherConstant.DEBIT + glcode))
            // changed since equals does considers decimal values eg 20.0 is
            // not equal to 2
            if (subledAmtmap.get(VoucherConstant.DEBIT + glcode)
                    .compareTo(accDetAmtMap.get(VoucherConstant.DEBIT + glcode)) != 0)
                throw new ApplicationRuntimeException(
                        "Total of subleger debit amount is not matching with the account code amount "
                                + glcode);
        if (null != subledAmtmap.get(VoucherConstant.CREDIT + glcode))
            // changed since equals does considers decimal values eg 20.0 is
            // not equal to 2
            if (subledAmtmap.get(VoucherConstant.CREDIT + glcode)
                    .compareTo(accDetAmtMap.get(VoucherConstant.CREDIT + glcode)) != 0)
                throw new ApplicationRuntimeException(
                        "Total of subleger credit amount is not matching with the account code amount "
                                + glcode);

    }
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("END | validateTransaction");

}