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.gbif.portal.dao.taxonomy.impl.hibernate.TaxonNameDAOImpl.java

License:Open Source License

/**
 * @see org.gbif.portal.dao.taxonomy.TaxonNameDAO#getTaxonNameFor(long)
 *///from ww w .  ja  v a  2 s  .  c o m
public TaxonName getTaxonNameFor(final long taxonNameId) {
    HibernateTemplate template = getHibernateTemplate();
    return (TaxonName) template.execute(new HibernateCallback() {
        public Object doInHibernate(Session session) {
            Query query = session.createQuery("from TaxonName where id = ?");
            query.setParameter(0, taxonNameId);
            query.setCacheable(true);
            return query.uniqueResult();
        }
    });
}

From source file:org.gbif.portal.dao.taxonomy.impl.hibernate.TaxonNameDAOImpl.java

License:Open Source License

/**
 * @see org.gbif.portal.dao.taxonomy.TaxonNameDAO#findScientificNames(java.lang.String, org.gbif.portal.model.taxonomy.TaxonRank, int, int)
 *///from w w w.  j  a va 2s  .  co m
@SuppressWarnings("unchecked")
public List<String> findScientificNamesInTaxonomy(final String nameStub, final boolean fuzzy,
        final TaxonRank taxonRank, final Boolean higherThanRankSupplied, final boolean soundex,
        final Long dataProviderId, final Long dataResourceId, final boolean allowUnconfirmed,
        final int startIndex, final int maxResults) {
    HibernateTemplate template = getHibernateTemplate();
    return (List<String>) template.execute(new HibernateCallback() {
        public Object doInHibernate(Session session) {
            StringBuffer sb = new StringBuffer();
            sb.append("select distinct tn.canonical from TaxonConcept tc inner join tc.taxonName tn where ");
            if (soundex)
                sb.append("tn.searchableCanonical like :nameStub");
            else
                sb.append(" tn.canonical like :nameStub");
            if (taxonRank != null) {
                sb.append(" and tn.taxonRank ");
                if (higherThanRankSupplied != null) {
                    if (higherThanRankSupplied) {
                        sb.append(" < ");
                    } else {
                        sb.append(" > ");
                    }
                } else {
                    sb.append(" = ");
                }
                sb.append(" :taxonRank");
            }

            if (dataProviderId != null) {
                sb.append(" and tc.dataProviderId= :dataProviderId");
            }

            if (dataResourceId != null) {
                sb.append(" and tc.dataResourceId= :dataResourceId");
            }

            if (allowUnconfirmed) {
                sb.append(" and tc.taxonomicPriority <= " + taxonomicPriorityThreshold);
            }

            Query query = session.createQuery(sb.toString());

            // use the sound ex algorithm if necessary
            String nameStubForQuery = nameStub;
            if (soundex) {
                nameStubForQuery = taxonNameSoundEx.soundEx(nameStub);
            }
            if (fuzzy && !soundex)
                query.setParameter("nameStub", nameStubForQuery + '%');
            else
                query.setParameter("nameStub", nameStubForQuery);
            if (taxonRank != null)
                query.setParameter("taxonRank", taxonRank);
            if (dataProviderId != null)
                query.setParameter("dataProviderId", dataProviderId);
            if (dataResourceId != null)
                query.setParameter("dataResourceId", dataResourceId);

            query.setCacheable(true);
            query.setMaxResults(maxResults);
            query.setFirstResult(startIndex);
            return query.list();
        }
    });
}

From source file:org.gbif.portal.dao.taxonomy.impl.hibernate.TaxonNameDAOImpl.java

License:Open Source License

/**
 * @see org.gbif.portal.dao.taxonomy.TaxonNameDAO#findScientificNamesForRank(java.lang.String, org.gbif.portal.model.taxonomy.TaxonRank, int, int)
 *//*from   ww  w  . ja v a 2  s. c o  m*/
@SuppressWarnings("unchecked")
public List<String> findScientificNames(final String nameStub, final boolean fuzzy, final TaxonRank taxonRank,
        final Boolean higherThanRankSupplied, final boolean soundex, final int startIndex,
        final int maxResults) {
    HibernateTemplate template = getHibernateTemplate();
    return (List<String>) template.execute(new HibernateCallback() {
        public Object doInHibernate(Session session) {

            StringBuffer sb = new StringBuffer();
            sb.append("select distinct canonical from TaxonName where with_records = 1 and ");
            if (soundex)
                sb.append("searchableCanonical like :nameStub");
            else
                sb.append(" canonical like :nameStub");
            if (taxonRank != null) {
                sb.append(" and taxonRank ");
                if (higherThanRankSupplied != null) {
                    if (higherThanRankSupplied) {
                        sb.append(" < ");
                    } else {
                        sb.append(" > ");
                    }
                } else {
                    sb.append(" = ");
                }
                sb.append(" :taxonRank");
            }
            Query query = session.createQuery(sb.toString());

            // use the sound ex algorithm if necessary
            String nameStubForQuery = nameStub;
            if (soundex) {
                nameStubForQuery = taxonNameSoundEx.soundEx(nameStub);
            }
            if (fuzzy && !soundex)
                query.setParameter("nameStub", nameStubForQuery + '%');
            else
                query.setParameter("nameStub", nameStubForQuery);
            if (taxonRank != null)
                query.setParameter("taxonRank", taxonRank);
            query.setCacheable(true);
            query.setMaxResults(maxResults);
            query.setFirstResult(startIndex);
            return query.list();
        }
    });
}

From source file:org.geoserver.hibernate.AbstractHibFacade.java

License:Open Source License

protected Query query(Object... elems) {
    final StringBuilder builder = new StringBuilder();
    int cnt = 0;//w ww  .  j  a  va2s.c o m
    for (Object elem : elems) {
        if (elem instanceof String) {
            builder.append(elem);
        } else if (elem instanceof Class) {
            Class clazz = (Class) elem;
            ClassMappings map = ClassMappings.fromInterface(clazz);
            if (map != null) {
                clazz = map.getImpl();
            }

            builder.append(clazz.getSimpleName());
        } else if (elem instanceof QueryParam) {
            builder.append(":param").append(cnt++);
        }
    }

    Query query = sessionFactory.getCurrentSession().createQuery(builder.toString());
    query.setCacheable(true);

    cnt = 0;

    for (Object elem : elems) {
        if (elem instanceof QueryParam) {
            query.setParameter("param" + (cnt++), ((QueryParam) elem).param);
        }
    }

    return query;
}

From source file:org.geoserver.hibernate.AbstractHibFacade.java

License:Open Source License

protected Object first(final Query query, boolean doWarn) {
    query.setMaxResults(doWarn ? 2 : 1);
    query.setCacheable(true);

    List<?> result = query.list();
    if (result.isEmpty()) {
        return null;
    } else {//  w  w w  .  ja  v a 2 s. c om
        //TODO: add a flag to control exception
        if (result.size() > 1) {
            throw new RuntimeException("Expected 1 result from " + query + " but got " + result.size());

        }
        //            if (doWarn && result.size() > 1) {
        //                LOGGER.log(Level.WARNING, "Found too many items in result", new RuntimeException(
        //                        "Trace: Found too many items in query"));
        //            }

        Object ret = result.get(0);
        if (ret instanceof HibernateProxy) {
            HibernateProxy proxy = (HibernateProxy) ret;
            ret = proxy.getHibernateLazyInitializer().getImplementation();
        }

        if (LOGGER.isLoggable(Level.FINE)) {
            StringBuilder callerChain = new StringBuilder();
            for (StackTraceElement stackTraceElement : new Throwable().getStackTrace()) {
                if ("first".equals(stackTraceElement.getMethodName()))
                    continue;
                String cname = stackTraceElement.getClassName();
                if (cname.startsWith("org.spring"))
                    continue;
                cname = cname.substring(cname.lastIndexOf(".") + 1);
                callerChain.append(cname).append('.').append(stackTraceElement.getMethodName()).append(':')
                        .append(stackTraceElement.getLineNumber()).append(' ');
                // if(++num==10) break;
            }
            LOGGER.fine(
                    "FIRST -->" + ret.getClass().getSimpleName() + " --- " + ret + " { " + callerChain + "}");
        }
        return ret;
    }
}

From source file:org.geoserver.hibernate.AbstractHibFacade.java

License:Open Source License

protected <T> List<T> list(Class<T> clazz) {
    Query query = query("from ", clazz);
    query.setCacheable(true);

    List<?> result = query.list();
    return Collections.unmodifiableList((List<T>) result);
}

From source file:org.grails.orm.hibernate.GrailsHibernateTemplate.java

License:Apache License

/**
 * Prepare the given Query object, applying cache settings and/or a
 * transaction timeout.//from   w ww  .  java  2s  .c  o m
 *
 * @param query the Query object to prepare
 */
protected void prepareQuery(Query query) {
    if (cacheQueries) {
        query.setCacheable(true);
    }
    if (shouldPassReadOnlyToHibernate()) {
        query.setReadOnly(true);
    }
    SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);
    if (sessionHolder != null && sessionHolder.hasTimeout()) {
        query.setTimeout(sessionHolder.getTimeToLiveInSeconds());
    }
}

From source file:org.gridgain.examples.jpa.JpaHibernateExample.java

License:Apache License

/**
 * Executes example.//from ww w.  j  av a2s .c o m
 *
 * @param args Command line arguments, none required.
 * @throws GridException If example execution failed.
 */
public static void main(String[] args) throws Exception {
    // Start the GridGain node, run the example, and stop the node when finished.
    try (Grid grid = GridGain.start(JpaHibernateExampleNodeStartup.configuration())) {
        // We use a single session factory, but create a dedicated session
        // for each transaction or query. This way we ensure that L1 cache
        // is not used (L1 cache has per-session scope only).
        System.out.println();
        System.out.println(">>> Hibernate L2 cache example started.");

        URL hibernateCfg = new File(HIBERNATE_CFG).toURI().toURL();

        SessionFactory sesFactory = createHibernateSessionFactory(hibernateCfg);

        System.out.println();
        System.out.println(">>> Creating objects.");

        final long orgId;

        Session ses = sesFactory.openSession();

        try {
            Transaction tx = ses.beginTransaction();

            Organization organization = new Organization("TAX1", "BigBrother Inc.");

            organization.getEmployees().add(new Employee(organization, "Winston", "Smith"));

            ses.save(organization);

            tx.commit();

            // Create an organization object, store it in DB, and save the database-generated
            // object ID. You may try adding more objects in a similar way.
            orgId = organization.getId();
        } finally {
            ses.close();
        }

        // Output L2 cache and GridGain cache stats. You may notice that
        // at this point the object is not yet stored in L2 cache, because
        // the read was not yet performed.
        printStats(sesFactory);

        System.out.println();
        System.out.println(">>> Querying object by ID.");

        // Query organization by ID several times. First time we get an L2 cache
        // miss, and the data is queried from DB, but it is then stored
        // in cache and successive queries hit the cache and return
        // immediately, no SQL query is made.
        for (int i = 0; i < 3; i++) {
            ses = sesFactory.openSession();

            try {
                Transaction tx = ses.beginTransaction();

                Organization organization = (Organization) ses.get(Organization.class, orgId);

                System.out.println("User: " + organization);

                for (Employee employee : organization.getEmployees())
                    System.out.println("\tPost: " + employee);

                tx.commit();
            } finally {
                ses.close();
            }
        }

        // Output the stats. We should see 1 miss and 2 hits for
        // Organization and Collection object (stored separately in L2 cache).
        // The Employee is loaded with the collection, so it won't imply
        // a miss.
        printStats(sesFactory);

        // Query data with HQL. Should observe the same behaviour as with query-by-id.
        for (int i = 0; i < 3; i++) {
            ses = sesFactory.openSession();

            try {
                Query qry = ses.createQuery("from Employee e where e.firstName=:firstName");

                qry.setString("firstName", "Winston");

                qry.setCacheable(true);

                List lst = qry.list();

                for (Object o : lst) {
                    Employee next = (Employee) o;

                    System.out.println("Employee: " + next);
                }
            } finally {
                ses.close();
            }
        }

        printStats(sesFactory);
    }
}

From source file:org.grouter.domain.dao.spring.MessageDAOImpl.java

License:Apache License

public List<Message> findAllMessages() {
    String hsql = "from Message as m";
    Session session = getSession();// w w  w  . j a v  a 2  s.com
    Query qr = session.createQuery(hsql);
    qr.setCacheable(true);
    return (List<Message>) qr.list();
}

From source file:org.hyperic.hq.measurement.server.session.MeasurementDAO.java

License:Open Source License

/**
 * @param tids - {@link Integer[]} of templateIds
 * @param iids - {@link Integer[]} of AppdefEntityIds
 * @param onlyEnabled - only selects enabled measurements
 *//*from  www. j  ava 2s .c  om*/
@SuppressWarnings("unchecked")
List<Measurement> findMeasurements(Integer[] tids, Integer[] iids, boolean onlyEnabled) {
    final IntegerType iType = new IntegerType();
    // sort to take advantage of query cache
    final List<Integer> iidList = new ArrayList<Integer>(Arrays.asList(iids));
    final List<Integer> tidList = new ArrayList<Integer>(Arrays.asList(tids));
    Collections.sort(tidList);
    Collections.sort(iidList);
    final StringBuilder buf = new StringBuilder(32).append("select m from Measurement m ")
            .append("join m.template t ").append("where m.instanceId in (:iids) AND t.id in (:tids)");
    if (onlyEnabled) {
        buf.append(" and enabled = :enabled");
    }
    final String sql = buf.toString();
    final List<Measurement> rtn = new ArrayList<Measurement>(iidList.size());
    final int batch = BATCH_SIZE / 2;
    for (int xx = 0; xx < iidList.size(); xx += batch) {
        final int iidEnd = Math.min(xx + batch, iidList.size());
        for (int yy = 0; yy < tidList.size(); yy += batch) {
            final int tidEnd = Math.min(yy + batch, tidList.size());
            Query query = getSession().createQuery(sql)
                    .setParameterList("iids", iidList.subList(xx, iidEnd), iType)
                    .setParameterList("tids", tidList.subList(yy, tidEnd), iType);
            if (onlyEnabled) {
                query.setBoolean("enabled", onlyEnabled);
            }
            rtn.addAll(query.setCacheable(true).setCacheRegion("Measurement.findMeasurements").list());
        }
    }
    return rtn;
}