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:dk.dma.ais.abnormal.event.db.jpa.JpaEventRepository.java

License:Open Source License

@Override
public <T extends Event> T findOngoingEventByVessel(int mmsi, Class<T> eventClass) {
    Session session = getSession();//from w  ww  .j  a  v a 2  s  .com

    T event = null;
    try {
        Query query = session.createQuery(
                "SELECT e FROM Event e LEFT JOIN e.behaviours b WHERE TYPE(e) = :clazz AND e.state = :state AND b.vessel.mmsi = :mmsi AND e.suppressed=false");
        query.setCacheable(true);
        query.setParameter("clazz", eventClass);
        query.setString("state", "ONGOING");
        query.setInteger("mmsi", mmsi);
        List events = query.list();

        if (events.size() > 0) {
            if (events.size() > 1) {
                LOG.warn("More than one (" + events.size() + ") ongoing event of type " + eventClass
                        + "; expected max. 1. Using first.");
            }
            event = (T) events.get(0);
        }

    } finally {
        session.close();
        LOG.debug("Database session closed: " + session);
    }

    return event;
}

From source file:edu.emory.library.tast.db.TastDbQuery.java

License:Open Source License

public Query getQuery(Session session, boolean useSQL) {

    ConditionResponse response;//  w  w w.ja  va2 s. c  om
    Query query;

    if (!useSQL) {
        response = toStringWithParams();
        query = session.createQuery(response.conditionString.toString());
    } else {
        response = toSQLStringWithParams();
        query = session.createSQLQuery(response.conditionString.toString());
    }

    Iterator iter = response.parameters.keySet().iterator();
    while (iter.hasNext()) {
        String param = iter.next().toString();
        query.setParameter(param, response.parameters.get(param));
    }

    if (!useSQL) {

        if (this.limit != LIMIT_NO_LIMIT) {
            query.setMaxResults(this.limit);
        }

        if (this.firstResult != FIRST_NO_FIRST) {
            query.setFirstResult(this.firstResult);
        }

    }

    query.setCacheable(this.isCacheable());

    return query;

}

From source file:edu.ur.hibernate.ir.institution.db.HbInstitutionalItemDAO.java

License:Apache License

/**
 * Get a list of items for a specified repository by name.
 * /*w w  w.  j av  a  2  s  .com*/
 * @param rowStart - Start row to fetch the data from
 * @param maxResulsts - maximum number of results to fetch
 * @param repositoryId - id of the collection to get items 
 * @param orderType - The order to sort by (ascending/descending)
 * 
 * @return List of institutional items
 */
@SuppressWarnings("unchecked")
public List<InstitutionalItem> getRepositoryItemsByName(final int rowStart, final int maxResults,
        final Long repositoryId, final OrderType orderType) {
    Session session = hbCrudDAO.getSessionFactory().getCurrentSession();

    Query q = null;
    if (orderType.equals(OrderType.DESCENDING_ORDER)) {
        q = session.getNamedQuery("getRepositoryItemsByNameOrderDesc");
    } else {
        q = session.getNamedQuery("getRepositoryItemsByNameOrderAsc");
    }
    q.setLong("repositoryId", repositoryId);
    q.setFirstResult(rowStart);
    q.setMaxResults(maxResults);
    q.setCacheable(false);
    q.setReadOnly(true);
    q.setFetchSize(maxResults);
    return q.list();

}

From source file:edu.ur.hibernate.ir.institution.db.HbInstitutionalItemDAO.java

License:Apache License

/**
 * Get a list of items for a specified repository by publication date.
 * /*from  w  w w  .  j av a  2s. c  o  m*/
 * @param rowStart - Start row to fetch the data from
 * @param maxResulsts - maximum number of results to fetch
 * @param repositoryId - id of the collection to get items 
 * @param orderType - The order to sort by (ascending/descending)
 * 
 * @return List of institutional items
 */
@SuppressWarnings("unchecked")
public List<InstitutionalItem> getRepositoryItemsPublicationDateOrder(int rowStart, int maxResults,
        Long repositoryId, OrderType orderType) {
    Query q = null;
    if (orderType.equals(OrderType.DESCENDING_ORDER)) {
        q = hbCrudDAO.getSessionFactory().getCurrentSession()
                .getNamedQuery("getRepositoryItemsByPublicationDateOrderDesc");
    } else {
        q = hbCrudDAO.getSessionFactory().getCurrentSession()
                .getNamedQuery("getRepositoryItemsByPublicationDateOrderAsc");
    }
    q.setLong("repositoryId", repositoryId);
    q.setFirstResult(rowStart);
    q.setMaxResults(maxResults);
    q.setCacheable(false);
    q.setReadOnly(true);
    q.setFetchSize(maxResults);
    return (List<InstitutionalItem>) q.list();
}

From source file:edu.ur.hibernate.ir.statistics.db.HbFileDownloadInfoDAO.java

License:Apache License

/**
 * This retrieves all file download info objects that are currently in the ignore
 * ip ranges./*from www.j av  a2 s . co m*/
 * 
 * @return the list of file download info objects that are ignored.
 * @see edu.ur.ir.statistics.FileDownloadInfoDAO#getAllDownloadInfoIgnored()
 */
@SuppressWarnings("unchecked")
public List<FileDownloadInfo> getDownloadInfoIgnored(final int rowStart, final int maxResults) {

    List<FileDownloadInfo> foundItems = (List<FileDownloadInfo>) hbCrudDAO.getHibernateTemplate()
            .execute(new HibernateCallback() {
                public Object doInHibernate(Session session) throws HibernateException, SQLException {
                    Query q = session.getNamedQuery("getFileDownloadsIgnored");
                    q.setFirstResult(rowStart);
                    q.setMaxResults(maxResults);
                    q.setCacheable(false);
                    q.setReadOnly(true);
                    q.setFetchSize(maxResults);
                    return q.list();
                }
            });
    return foundItems;
}

From source file:edu.ur.hibernate.ir.statistics.db.HbFileDownloadRollUpProcessingRecordDAO.java

License:Apache License

@SuppressWarnings("unchecked")
public List<FileDownloadRollUpProcessingRecord> getProcessingRecords(final int start, final int maxResults) {
    return (List<FileDownloadRollUpProcessingRecord>) hbCrudDAO.getHibernateTemplate()
            .execute(new HibernateCallback() {
                public Object doInHibernate(Session session) throws HibernateException, SQLException {
                    Query q = session.getNamedQuery("getAllFileDownloadRollUpProcessingRecords");
                    q.setReadOnly(true);
                    q.setCacheable(false);
                    q.setFirstResult(start);
                    q.setMaxResults(maxResults);
                    q.setFetchSize(maxResults);
                    return (List<FileDownloadRollUpProcessingRecord>) q.list();
                }//  w ww. ja va 2 s . c  om
            });
}

From source file:edu.ur.hibernate.ir.statistics.db.HbIpIgnoreFileDownloadInfoDAO.java

License:Apache License

@SuppressWarnings("unchecked")
public List<IpIgnoreFileDownloadInfo> getIgnoreInfoNowAcceptable(final int rowStart, final int maxResults) {

    List<IpIgnoreFileDownloadInfo> foundItems = (List<IpIgnoreFileDownloadInfo>) hbCrudDAO
            .getHibernateTemplate().execute(new HibernateCallback() {
                public Object doInHibernate(Session session) throws HibernateException, SQLException {
                    Query q = session.getNamedQuery("getAcceptableFileDownloadsIgnored");
                    q.setFirstResult(rowStart);
                    q.setMaxResults(maxResults);
                    q.setCacheable(false);
                    q.setReadOnly(true);
                    q.setFetchSize(maxResults);
                    return q.list();
                }// w w w  . j  a  v  a 2  s. c  o  m
            });
    return foundItems;
}

From source file:javaapplicationhibernate.JavaApplicationHibernate.java

/**
 * @param args the command line arguments
 *//*from   w  w  w.  j a  v  a  2s.c  o  m*/
public static void main(String[] args) {

    Session session = MiHibernateUtil.getSessionFactory().openSession();
    Transaction transaction = session.beginTransaction();

    Long id = null;
    Cliente cliente = new Cliente();

    double saldo = 5000;

    cliente.setNombre("Juan");
    cliente.setApellido("Perez");
    cliente.setEsClienteVip(true);
    cliente.setSaldo(saldo);
    cliente.setFechaAlta(new Date());

    id = (Long) session.save(cliente);
    System.out.println("Id generado " + id);

    Pedido pedido1 = new Pedido();
    pedido1.setSaldo(5000);
    pedido1.setCliente(cliente);

    session.save(pedido1);

    cliente.getPedidos().add(pedido1);
    session.update(cliente);

    transaction.commit();
    session.close();

    System.out.println("Recuperando cliente -------------------------------------------");

    session = MiHibernateUtil.getSessionFactory().openSession();
    cliente = (Cliente) session.load(Cliente.class, id);

    System.out.println(cliente.getNombre() + " " + cliente.getApellido());

    session.close();

    System.out.println("Recuperando pedidos -------------------------------------------");

    session = MiHibernateUtil.getSessionFactory().openSession();
    cliente = (Cliente) session.load(Cliente.class, id);

    System.out.println(cliente.getNombre() + " " + cliente.getApellido());
    for (Pedido p : cliente.getPedidos()) {
        System.out.println(p.getSaldo());
    }

    session.close();

    System.out.println("Recuperando pedidos -------------------------------------------");

    session = MiHibernateUtil.getSessionFactory().openSession();
    cliente = (Cliente) session.load(Cliente.class, id);

    System.out.println(cliente.getNombre() + " " + cliente.getApellido());

    for (Pedido p : cliente.getPedidos()) {
        System.out.println(p.getSaldo());
    }

    session.close();

    System.out.println("-------------------------------------------");

    session = MiHibernateUtil.getSessionFactory().openSession();
    Query query = session.createQuery("from Cliente as c");
    query.setCacheable(true);

    List<Cliente> clientes = query.list();

    for (Cliente c : clientes) {
        System.out.println(c.getNombre() + " " + c.getApellido());
    }

    session.close();

    System.out.println("-------------------------------------------");

    session = MiHibernateUtil.getSessionFactory().openSession();
    query = session.createQuery("from Cliente as c");
    query.setCacheable(true);

    clientes = query.list();

    for (Cliente c : clientes) {
        System.out.println(c.getNombre() + " " + c.getApellido());
    }

    session.close();

    MiHibernateUtil.getSessionFactory().close();
}

From source file:jp.gmo.zcom.ticket.dao.impl.BookTicketDaoImpl.java

License:Open Source License

/**
 * get list of match//  w  w  w  .j a v  a  2s. c  om
 * 
 * @param matchDate
 * @return list match
 */
@SuppressWarnings("unchecked")
@Override
public List<Match> getListMatch(Date matchDate) {
    Session session = this.sessionFactory.getCurrentSession();
    // Query get lesson
    Query query = session.getNamedQuery("BookTicketDao.searchListMatch");
    query.setCacheable(true);
    //query.setCacheRegion("BookTicketDao.searchListMatch");

    // Set parameter
    query.setDate("matchDate", matchDate);
    query.setParameter("status", ConstValues.STATUS_VALUES_ON);

    List<Match> result = query.list();
    return result;
}

From source file:jp.gmo.zcom.ticket.dao.impl.BookTicketDaoImpl.java

License:Open Source License

/**
 * get stadium by id// w w w .ja  v  a2  s.c  om
 * 
 * @param stadiumId
 * @return stadium
 */
@Override
public Stadium getStadiumById(Integer stadiumId) {
    Session session = this.sessionFactory.getCurrentSession();
    // Query get lesson
    Query query = session.getNamedQuery("BookTicketDao.searchStadiumById");
    query.setCacheable(true);
    //query.setCacheRegion("BookTicketDao.searchListMatch");

    // Set parameter
    query.setParameter("stadiumId", stadiumId);

    return (Stadium) query.uniqueResult();
}