Example usage for org.hibernate Session clear

List of usage examples for org.hibernate Session clear

Introduction

In this page you can find the example usage for org.hibernate Session clear.

Prototype

void clear();

Source Link

Document

Completely clear the session.

Usage

From source file:br.ufg.calendario.dao.InteressadoDao.java

@Transactional
public boolean excluir(Interessado interessado) {
    Session session = this.sessionFactory.getCurrentSession();
    try {//from   w  w  w.ja v a2 s .com
        session.delete(interessado);
        return true;
    } catch (HibernateException e) {
        System.out.println(e.getMessage());
        session.clear();
        return false;
    }
}

From source file:br.ufg.calendario.dao.UsuarioDao.java

@Transactional
public boolean adicionar(Usuario usuario) {
    Session session = sessionFactory.getCurrentSession();
    try {// w ww . j av a 2  s . c o m
        session.clear();
        session.save(usuario);
        return true;
    } catch (HibernateException e) {
        System.out.println(e.getMessage());
        session.clear();
        return false;
    }
}

From source file:br.ufg.calendario.dao.UsuarioDao.java

@Transactional
public boolean atualizar(Usuario usuario) {
    Session session = sessionFactory.getCurrentSession();
    try {/* w ww  . j  av  a  2  s.co  m*/
        session.clear();
        session.update(usuario);
        return true;
    } catch (HibernateException e) {
        System.out.println(e.getMessage());
        session.clear();
        return false;
    }
}

From source file:br.ufg.calendario.dao.UsuarioDao.java

@Transactional
public boolean excluir(Usuario usuario) {
    Session session = sessionFactory.getCurrentSession();
    try {/*from   ww w.java 2s .co  m*/
        session.delete(usuario);
        return true;
    } catch (HibernateException e) {
        System.out.println(e.getMessage());
        session.clear();
        return false;
    }
}

From source file:br.ufg.reqweb.dao.PeriodoDao.java

private void disableOthers(Session session, Periodo periodo) {
    Criteria criteria = session.createCriteria(Periodo.class);
    List<Periodo> periodoList = criteria.list();
    int counter = 0;
    for (Periodo p : periodoList) {
        if (!Objects.equals(p.getId(), periodo.getId())) {
            p.setAtivo(false);/*from ww w.j av a2s . co  m*/
            session.save(p);
        }
        if (++counter % 20 == 0) {
            session.flush();
            session.clear();
        }
    }
}

From source file:ca.myewb.build.CreateDb.java

License:Open Source License

private static void controllerData()
        throws InstantiationException, IllegalAccessException, ClassNotFoundException {
    /* Dynamically find & add all pages (controllers)
     * This is done by directory listing... a bit of a hack,
     *  but good enough./* w  ww.j a  va 2 s  .  c  o  m*/
     *
     * This assumes the only files in controllers that aren't
     * pages are the CVS directories, and that directories are only
     * one level deep.
     */
    System.out.println("Inserting controller data");

    Session session = HibernateUtil.currentSession();

    // Clear the perms table first.
    Iterator pages = session.createQuery("FROM PageModel").list().iterator();

    while (pages.hasNext()) {
        ((PageModel) pages.next()).clearGroups();
    }

    session.flush();
    session.createQuery("DELETE PageModel").executeUpdate();
    session.flush();
    session.clear();

    // And re-populate it
    File f = new File("WEB-INF/src/ca/myewb/controllers");
    String[] dirs = f.list();

    System.out.println("Using controllers directory " + f.getAbsolutePath());

    for (String pkgName : dirs) {
        if (!pkgName.equals(".svn") && !pkgName.equals("common")) {
            String[] files = new File("WEB-INF/src/ca/myewb/controllers/" + pkgName).list();
            for (String fileName : files) {
                if (!fileName.substring(0, 1).equals(".")) {
                    File theFile = new File("WEB-INF/src/ca/myewb/controllers/" + pkgName + "/" + fileName);
                    if (!theFile.isDirectory()) {
                        fileName = fileName.substring(0, fileName.length() - 5);
                        putPageInDatabase(session, pkgName, fileName);
                    } else {
                        String[] files2 = new File(
                                "WEB-INF/src/ca/myewb/controllers/" + pkgName + "/" + fileName).list();
                        for (String fileName2 : files2) {
                            if (!fileName2.substring(0, 1).equals(".")) {
                                fileName2 = fileName2.substring(0, fileName2.length() - 5);
                                putPageInDatabase(session, pkgName, fileName + "." + fileName2);
                            }
                        }
                    }
                }
            }
        }
    }
}

From source file:ca.myewb.frame.HibernateUtil.java

License:Open Source License

public static void closeSession() throws HibernateException {
    try {//from w  w  w.  j a  v  a 2s. co  m
        Session s = sessionHolder.get();
        sessionHolder.set(null);

        // Close the session if one exists
        if (s != null) {
            s.clear();
            s.close();
        }
    } catch (Exception ex) {
        log.fatal("Problem closing session");
        throw new HibernateException(ex);
    }
}

From source file:ca.ualberta.physics.cssdp.catalogue.dao.UrlDataProductDao.java

License:Apache License

public void process(UrlDataProductUpdateMap urlDataProductUpdateMap) {

    if (urlDataProductUpdateMap.getUrls().size() == 0) {
        return;/*from w  ww  . j ava 2  s .  co m*/
    }

    /*
     * The size of scannedUrlDataProducts should be <= jdbc batch size
     * configured.
     */

    // we have to resort to hibernate directly because JPA does not have
    // scrolling capability
    Session session = emp.get().unwrap(Session.class).getSessionFactory().openSession();

    Transaction tx = session.beginTransaction();

    // "in" clause limit is 2^16 on Postgresql, it might be different on
    // other dbs
    String hqlString = "from UrlDataProduct urldp where urldp.url in (:urls)";

    // the fastest way to scroll through the existing data
    Query q = session.createQuery(hqlString);
    q.setParameterList("urls", urlDataProductUpdateMap.getUrls());
    q.setCacheMode(CacheMode.IGNORE);
    ScrollableResults existingData = q.scroll(ScrollMode.FORWARD_ONLY);

    while (existingData.next()) {

        UrlDataProduct existing = (UrlDataProduct) existingData.get(0);
        UrlDataProduct updated = urlDataProductUpdateMap.get(existing.getUrl());

        if (updated != null) {

            /*
             * Only bother to update the record if it's actually changed.
             * Note that the scan timestamp is ignored in the check because
             * that isn't something the provider changed. A change can also
             * mean the url was deleted, and now it's back.
             */
            if (existing.hasChanged(updated)) {
                // existing.setDataProduct(updated.getDataProduct());
                existing.setUrl(updated.getUrl());
                existing.setStartTimestamp(updated.getStartTimestamp());
                existing.setEndTimestamp(updated.getEndTimestamp());
                existing.setScanTimestamp(updated.getScanTimestamp());
                existing.setDeleted(false);
                urlDataProductUpdateMap.remove(updated.getUrl());
                session.update(existing);
            } else {
                // remove it so it's not duplicated
                urlDataProductUpdateMap.remove(existing.getUrl());
            }

        } else {

            // if we get here it means the existing url has been removed
            // from the server, set "delete" it from the catalogue
            existing.setDeleted(true);
            existing.setScanTimestamp(new LocalDateTime());

        }

    }

    // persist the new url mappings
    for (String newUrl : urlDataProductUpdateMap.getUrls()) {
        UrlDataProduct newUrlDataProduct = urlDataProductUpdateMap.get(newUrl);
        session.save(newUrlDataProduct);
        logger.debug("saved a mapping: " + newUrlDataProduct.getUrl());
    }

    session.flush();
    session.clear();

    tx.commit();
    session.close();

}

From source file:ch.algotrader.dao.AbstractDao.java

License:Open Source License

public boolean deleteById(final long id) {

    Session currentSession = getCurrentSession();
    Query query = currentSession// w w  w  . j av  a 2s . com
            .createQuery("delete from " + this.entityClass.getSimpleName() + " where id = :id");
    query.setParameter("id", id);
    int result = query.executeUpdate();
    if (result > 0) {

        // Need to clear the session to ensure deleted entities are not stuck in the session cache
        currentSession.clear();
        return true;
    } else {

        return false;
    }
}

From source file:ch.systemsx.cisd.openbis.generic.server.dataaccess.db.search.DefaultFullTextIndexer.java

License:Apache License

public final <T> void doFullTextIndex(final Session hibernateSession, final Class<T> clazz)
        throws DataAccessException {
    operationLog.info(String.format("Indexing '%s'...", clazz.getSimpleName()));
    final FullTextSession fullTextSession = Search.getFullTextSession(hibernateSession);
    fullTextSession.setFlushMode(FlushMode.MANUAL);
    fullTextSession.setCacheMode(CacheMode.IGNORE);

    // we index entities in batches loading them in groups restricted by id:
    // [ ids[index], ids[min(index+batchSize, maxIndex))] )
    final Transaction transaction = hibernateSession.beginTransaction();
    final List<Long> ids = getAllIds(fullTextSession, clazz);
    final int idsSize = ids.size();
    operationLog.info(String.format("... got %d '%s' ids...", idsSize, clazz.getSimpleName()));
    int index = 0;
    final int maxIndex = idsSize - 1;
    // need to increment last id because we use 'lt' condition
    if (maxIndex > -1) {
        ids.set(maxIndex, ids.get(maxIndex) + 1);
    }/*www .  j ava  2 s .  com*/
    while (index < maxIndex) {
        final int nextIndex = getNextIndex(index, maxIndex);
        final long minId = ids.get(index);
        final long maxId = ids.get(nextIndex);
        final List<?> results = createCriteriaWithRestrictedId(fullTextSession, clazz, minId, maxId).list();
        for (Object object : results) {
            indexEntity(hibernateSession, fullTextSession, object);
            index++;
        }
        operationLog.info(String.format("%d '%s' have been indexed...", index, clazz.getSimpleName()));
        fullTextSession.flushToIndexes();
        hibernateSession.clear();
    }
    fullTextSession.getSearchFactory().optimize(clazz);
    transaction.commit();
    operationLog.info(
            String.format("'%s' index complete. %d entities have been indexed.", clazz.getSimpleName(), index));
}