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:de.powerstaff.business.service.impl.ProfileIndexerServiceImpl.java

License:Open Source License

/**
 * Run the indexer.//  ww  w.  j  ava2  s  .  c o  m
 */
@Transactional
public void runIndexer() {

    if (!systemParameterService.isIndexingEnabled()) {
        LOGGER.info("Indexing disabled");
        return;
    }

    if (running) {
        LOGGER.info("Indexing already running");
    }

    running = true;

    LOGGER.info("Running indexing");

    readerFactory.initialize();

    serviceLogger.logStart(SERVICE_ID, "");

    // Jetzt luft er

    long theStartTime = System.currentTimeMillis();

    try {

        int theFetchSize = 100;
        int theLogCount = theFetchSize * 10;

        Session theHibernateSession = sessionFactory.getCurrentSession();
        FullTextSession theFT = Search.getFullTextSession(theHibernateSession);

        org.hibernate.Query theQuery = theHibernateSession.createQuery("from Freelancer");
        theQuery.setFetchSize(theFetchSize);
        ScrollableResults theResults = theQuery.scroll(ScrollMode.FORWARD_ONLY);
        int counter = 0;
        while (theResults.next()) {
            Freelancer theFreelancer = (Freelancer) theResults.get(0);

            boolean needsToUpdate = true;

            TermQuery theTermQuery = new TermQuery(new Term("id", "" + theFreelancer.getId()));
            FullTextQuery theHibernateQuery = theFT.createFullTextQuery(theTermQuery, Freelancer.class);
            theHibernateQuery.setProjection(FullTextQuery.DOCUMENT);

            for (Object theSingleEntity : theHibernateQuery.list()) {

                needsToUpdate = false;
                Object[] theRow = (Object[]) theSingleEntity;
                Document theDocument = (Document) theRow[0];

                long theNumberOfProfiles = Long.parseLong(theDocument.get(ProfileIndexerService.NUM_PROFILES));
                List<FreelancerProfile> theProfiles = profileSearchService.loadProfilesFor(theFreelancer);
                if (theNumberOfProfiles != theProfiles.size()) {
                    LOGGER.info("Updating freelancer " + theFreelancer.getId()
                            + " as the number of profiles changed from " + theNumberOfProfiles + " to "
                            + theProfiles.size());
                    needsToUpdate = true;
                } else {
                    for (int i = 1; i <= theNumberOfProfiles; i++) {
                        String theFileName = theDocument.get(ProfileIndexerService.PROFILE_PATH_PREFIX + i);
                        File theFileOnServer = new File(theFileName);
                        if (theFileOnServer.exists()) {
                            long theModification = Long.parseLong(
                                    theDocument.get(ProfileIndexerService.PROFILE_MODIFICATION_PREFIX + i));
                            long theLastModified = theFileOnServer.lastModified() / 1000;
                            if (theModification != theLastModified) {
                                LOGGER.info("Updating freelancer " + theFreelancer.getId() + " as profile "
                                        + theFileOnServer + " was modified");
                                needsToUpdate = true;
                            }
                        } else {
                            LOGGER.info("Updating freelancer " + theFreelancer.getId() + " as profile "
                                    + theFileOnServer + " seems to be deleted");
                            needsToUpdate = true;
                        }
                    }
                }

            }

            if (needsToUpdate) {
                theFT.index(theFreelancer);
            }

            if (counter % theLogCount == 0) {
                LOGGER.info("Processing record " + counter);
            }

            if (counter % theFetchSize == 0) {

                LOGGER.debug("Flushing session and index");
                theFT.flushToIndexes();
                theFT.clear();
                theHibernateSession.clear();
            }
            counter++;
        }

    } catch (Exception ex) {

        LOGGER.error("Error on indexing", ex);

    } finally {

        theStartTime = System.currentTimeMillis() - theStartTime;

        LOGGER.info("Indexing finished");

        serviceLogger.logEnd(SERVICE_ID, "Dauer = " + theStartTime + "ms");

        running = false;
    }
}

From source file:de.powerstaff.business.service.impl.WrongDataServiceImpl.java

License:Open Source License

private void processFreelancer(File aReportFile) throws FileNotFoundException, ParseException {

    File theDBOhneProfil = new File(aReportFile, "Freiberufler_mit_Code_ohne_Profil.csv");
    File theFreelancerOhneNewsletter = new File(aReportFile, "Freiberufler_ohne_Newsletter.csv");
    File theFreelancerMitHomepageOhneKontakt = new File(aReportFile,
            "Freiberufler_mit_Homepage_ohne_Kontakt.csv");
    File theFreelancerForNewsletter = new File(aReportFile, "Freiberufler_fr_Newsletter.csv");
    File theProfileOhneDB = new File(aReportFile, "Profile_ohne_Datenbankeintrag.csv");
    File theProfileDoppelterCode = new File(aReportFile, "Profile_Kodierung_doppelt.csv");

    PrintWriter theDBOhneProfilWriter = null;
    PrintWriter theFreelancerOhneNewsletterWriter = null;
    PrintWriter theFreelancerMitHomepageOhneKontaktWriter = null;
    PrintWriter theFreelancerForNewsletterWriter = null;
    PrintWriter theProfileOhneDBWriter = null;
    PrintWriter theProfileDoppelterCodeWriter = null;

    FreelancerBackingBeanDataModel theModel = new FreelancerBackingBeanDataModel();

    try {/*from w ww .  j av  a  2  s  .  c  o m*/

        theProfileDoppelterCodeWriter = new PrintWriter(theProfileDoppelterCode);

        theDBOhneProfilWriter = new PrintWriter(theDBOhneProfil);
        theFreelancerOhneNewsletterWriter = new PrintWriter(theFreelancerOhneNewsletter);
        theFreelancerMitHomepageOhneKontaktWriter = new PrintWriter(theFreelancerMitHomepageOhneKontakt);
        theFreelancerForNewsletterWriter = new PrintWriter(theFreelancerForNewsletter);
        theProfileOhneDBWriter = new PrintWriter(theProfileOhneDB);

        theDBOhneProfilWriter.println("Kodierung;Name;Vorname;Kreditor");
        theFreelancerOhneNewsletterWriter.println("Kodierung;Name;Vorname;Mail");
        theFreelancerMitHomepageOhneKontaktWriter.println("Kodierung;Name;Vorname;Homepage");
        theFreelancerForNewsletterWriter.println(
                "Krzel;Name;Vorname;Titel;eMail;Eintrag in Kreditor;Verfgbarkeit;Homepage;letzter Kontakt;Status;Xing;Gulp");
        theProfileOhneDBWriter.println("Kodierung;Dateinamen");
        theProfileDoppelterCodeWriter.println("Kodierung;Dateinamen");

        boolean newsletterEnabled = systemParameterService.isNewsletterEnabled();
        Set<String> theMails = new HashSet<String>();
        Date theStartDate = null;

        DateFormat theDateFormat = new SimpleDateFormat("dd.MM.yyyy");

        if (newsletterEnabled) {
            theStartDate = theDateFormat.parse(systemParameterService.getStartDateForNotInNewsletter());

            for (NewsletterMail theMail : websiteDao.getConfirmedMails()) {
                theMails.add(theMail.getMail().toLowerCase());
            }

        }

        Session theSession = sessionFactory.getCurrentSession();
        int theFetchSize = 100;
        int theLogCount = theFetchSize * 10;

        Query theQuery = theSession.createQuery("from Freelancer");
        theQuery.setFetchSize(theFetchSize);
        ScrollableResults theResults = theQuery.scroll(ScrollMode.FORWARD_ONLY);
        int counter = 0;

        Set<String> theKnownCodes = new HashSet<String>();

        while (theResults.next()) {
            Freelancer theFreelancer = (Freelancer) theResults.get(0);

            String theCode = theFreelancer.getCode();
            if (!StringUtils.isEmpty(theCode)) {
                theCode = theCode.toLowerCase();
                theKnownCodes.add(theCode);

                Set<File> theFiles = fsCache.getFilesForCode(theCode);
                if ((theFiles == null || theFiles.size() == 0)) {
                    theDBOhneProfilWriter.println(theCode + ";" + saveString(theFreelancer.getName1()) + ";"
                            + saveString(theFreelancer.getName2()) + ";"
                            + saveString(theFreelancer.getKreditorNr()));
                }
            }

            List<FreelancerContact> theMailContacts = theFreelancer.getEMailContacts();
            List<FreelancerContact> theWebContacts = theFreelancer.getWebContacts();

            Date theLastContact = theFreelancer.getLastContactDate();

            if (!theFreelancer.isContactforbidden()) {

                String theMail = null;
                for (FreelancerContact theContact : theMailContacts) {
                    if (StringUtils.isEmpty(theMail)
                            && "eMail".equalsIgnoreCase(theContact.getType().getDescription())) {
                        theMail = theContact.getValue();
                    }
                }
                String theWeb = "";
                for (FreelancerContact theContact : theWebContacts) {
                    if (StringUtils.isEmpty(theWeb)
                            && "Web".equalsIgnoreCase(theContact.getType().getDescription())) {
                        theWeb = theContact.getValue();
                    }
                }
                String theGulp = "";
                for (FreelancerContact theContact : theWebContacts) {
                    if (StringUtils.isEmpty(theWeb)
                            && "Gulp".equalsIgnoreCase(theContact.getType().getDescription())) {
                        theGulp = theContact.getValue();
                    }
                }

                String theXing = "";
                for (FreelancerContact theContact : theWebContacts) {
                    if (StringUtils.isEmpty(theWeb)
                            && "Xing".equalsIgnoreCase(theContact.getType().getDescription())) {
                        theXing = theContact.getValue();
                    }
                }

                String theAvailable = "";
                Date theAvailability = theFreelancer.getAvailabilityAsDate();
                if (theAvailability != null) {
                    theAvailable = theDateFormat.format(theAvailability);
                }

                theFreelancerForNewsletterWriter.print(saveString(theFreelancer.getCode()));
                theFreelancerForNewsletterWriter.print(";");
                theFreelancerForNewsletterWriter.print(saveString(theFreelancer.getName1()));
                theFreelancerForNewsletterWriter.print(";");
                theFreelancerForNewsletterWriter.print(saveString(theFreelancer.getName2()));
                theFreelancerForNewsletterWriter.print(";");
                theFreelancerForNewsletterWriter.print(saveString(theFreelancer.getTitel()));
                theFreelancerForNewsletterWriter.print(";");
                theFreelancerForNewsletterWriter.print(saveString(theMail));
                theFreelancerForNewsletterWriter.print(";");
                theFreelancerForNewsletterWriter.print(saveString(theFreelancer.getKreditorNr()));
                theFreelancerForNewsletterWriter.print(";");
                theFreelancerForNewsletterWriter.print(saveString(theAvailable));
                theFreelancerForNewsletterWriter.print(";");
                theFreelancerForNewsletterWriter.print(saveString(theWeb));
                theFreelancerForNewsletterWriter.print(";");
                theFreelancerForNewsletterWriter.print(saveString(theLastContact));
                theFreelancerForNewsletterWriter.print(";");
                theFreelancerForNewsletterWriter
                        .print(saveString(theModel.getStatusAsString(theFreelancer.getStatus())));
                theFreelancerForNewsletterWriter.print(";");
                theFreelancerForNewsletterWriter.print(saveString(theXing));
                theFreelancerForNewsletterWriter.print(";");
                theFreelancerForNewsletterWriter.print(saveString(theGulp));
                theFreelancerForNewsletterWriter.println();
            }

            if (newsletterEnabled) {

                if (theLastContact != null && !theFreelancer.isContactforbidden()) {

                    String theMail = "";

                    boolean hasMail = false;
                    for (FreelancerContact theContact : theMailContacts) {
                        theMail = theContact.getValue();
                        if (theMails.contains(theMail.toLowerCase())) {
                            hasMail = true;
                        }
                    }

                    if (!hasMail) {
                        theFreelancerOhneNewsletterWriter.println(theFreelancer.getCode() + ";"
                                + theFreelancer.getName1() + ";" + theFreelancer.getName2() + ";" + theMail);
                    }
                }
            }

            if (theLastContact == null) {

                boolean hasHomepage = false;
                String theHomepage = null;
                for (FreelancerContact theContact : theWebContacts) {
                    theHomepage = theContact.getValue();
                    hasHomepage = true;
                }

                if (hasHomepage) {
                    theFreelancerMitHomepageOhneKontaktWriter.println(theFreelancer.getCode() + ";"
                            + theFreelancer.getName1() + ";" + theFreelancer.getName2() + ";" + theHomepage);
                }

            }

            if (counter % theLogCount == 0) {
                LOGGER.info("Processing record " + counter);
            }

            if (counter % theFetchSize == 0) {

                LOGGER.debug("Flushing session");
                theSession.clear();
            }
            counter++;
        }

        Set<String> theCodesFromFiles = new HashSet<String>();
        theCodesFromFiles.addAll(fsCache.getKnownCodes());
        for (String theCode : theCodesFromFiles) {
            Set<File> theFiles = fsCache.getFilesForCode(theCode);
            if (theFiles != null && theFiles.size() > 1) {
                // Doppelter Code
                StringBuilder theBuilder = new StringBuilder();
                for (File theFile : theFiles) {
                    if (theBuilder.length() > 0) {
                        theBuilder.append(";");
                    }
                    theBuilder.append(theFile.toString());
                }
                theProfileDoppelterCodeWriter.println(theCode + ";" + theBuilder);
            }
        }

        theCodesFromFiles.removeAll(theKnownCodes);

        for (String theCode : theCodesFromFiles) {
            Set<File> theFiles = fsCache.getFilesForCode(theCode);
            if (theFiles != null) {
                for (File theFile : theFiles) {
                    theProfileOhneDBWriter.println(theCode + ";" + theFile);
                }
            }
        }
    } catch (Exception e) {
        LOGGER.error("Error processing freelancer", e);
    } finally {
        IOUtils.closeQuietly(theDBOhneProfilWriter);
        IOUtils.closeQuietly(theFreelancerOhneNewsletterWriter);
        IOUtils.closeQuietly(theFreelancerMitHomepageOhneKontaktWriter);
        IOUtils.closeQuietly(theFreelancerForNewsletterWriter);
        IOUtils.closeQuietly(theProfileOhneDBWriter);
        IOUtils.closeQuietly(theProfileDoppelterCodeWriter);
    }
}

From source file:de.rwth.idsg.xsharing.router.persistence.repository.AbstractRepository.java

License:Open Source License

protected <T> void saveBatch(List<T> entities) throws DatabaseException {
    Session session = null;
    Transaction tx = null;/* w  w  w. jav  a  2s  .c o  m*/

    try {
        session = getEntityManager().unwrap(Session.class);
        // session.setCacheMode(CacheMode.IGNORE);
        tx = session.beginTransaction();

        int counter = 0;
        for (T p : entities) {
            session.persist(p);
            if (++counter % BATCH_SIZE == 0) {
                // flush a batch of inserts and release memory
                session.flush();
                session.clear();
            }
        }

        tx.commit();

    } catch (Exception e) {
        if (tx != null) {
            try {
                tx.rollback();
            } catch (RuntimeException rbe) {
                log.error("Couldn't roll back transaction", rbe);
            }
        }
        throw new DatabaseException("Batch saving of entity list failed: " + e.getMessage());

    } finally {
        if (session != null && session.isOpen()) {
            try {
                session.close();
            } catch (HibernateException e) {
                log.error("Error while trying to close the session", e);
            }
        }
    }
}

From source file:de.sub.goobi.forms.BenutzergruppenForm.java

License:Open Source License

/**
 * Display all user groups with any filtering.
 *
 * @return page or empty String//from w w  w  .j av a2s  . c o  m
 */
public String FilterKein() {
    try {
        Session session = Helper.getHibernateSession();
        session.clear();
        Criteria crit = session.createCriteria(UserGroup.class);
        crit.addOrder(Order.asc("title"));
        this.page = new Page(crit, 0);
    } catch (HibernateException he) {
        Helper.setFehlerMeldung("Error, could not read", he.getMessage());
        return "";
    }
    return "BenutzergruppenAlle";
}

From source file:de.sub.goobi.forms.DocketForm.java

License:Open Source License

/**
 * No filter./* www  .  j av a 2  s. c o m*/
 *
 * @return page or empty String
 */
public String FilterKein() {
    try {
        // HibernateUtil.clearSession();
        Session session = Helper.getHibernateSession();
        // session.flush();
        session.clear();
        Criteria crit = session.createCriteria(Docket.class);
        crit.addOrder(Order.asc("name"));
        this.page = new Page(crit, 0);
    } catch (HibernateException he) {
        Helper.setFehlerMeldung("fehlerBeimEinlesen", he.getMessage());
        return "";
    }
    return "DocketList";
}

From source file:de.sub.goobi.forms.LdapGruppenForm.java

License:Open Source License

/**
 * No filter./*www  . j  av  a 2 s. c  om*/
 *
 * @return page or empty String
 */
public String FilterKein() {
    try {
        Session session = Helper.getHibernateSession();
        session.clear();
        Criteria crit = session.createCriteria(LdapGroup.class);
        crit.addOrder(Order.asc("title"));
        this.page = new Page(crit, 0);
    } catch (HibernateException he) {
        Helper.setFehlerMeldung("Error on reading database", he.getMessage());
        return "";
    }
    return "LdapGruppenAlle";
}

From source file:de.sub.goobi.forms.ProjekteForm.java

License:Open Source License

/**
 * No filter.// ww  w .  j a va 2s.c  om
 *
 * @return page or empty String
 */
public String FilterKein() {
    try {
        Session session = Helper.getHibernateSession();
        session.clear();
        Criteria crit = session.createCriteria(Project.class);
        crit.addOrder(Order.asc("title"));
        this.page = new Page(crit, 0);
    } catch (HibernateException he) {
        Helper.setFehlerMeldung("could not read", he.getMessage());
        myLogger.error(he.getMessage());
        return "";
    }
    return "ProjekteAlle";
}

From source file:de.sub.goobi.forms.RegelsaetzeForm.java

License:Open Source License

/**
 * No filtering.// w  w  w.  j a v a2  s .c  o  m
 *
 * @return page or empty String
 */
public String FilterKein() {
    try {
        Session session = Helper.getHibernateSession();
        session.clear();
        Criteria crit = session.createCriteria(Ruleset.class);
        crit.addOrder(Order.asc("title"));
        this.page = new Page(crit, 0);
    } catch (HibernateException he) {
        Helper.setFehlerMeldung("fehlerBeimEinlesen", he.getMessage());
        return "";
    }
    return "RegelsaetzeAlle";
}

From source file:de.sub.goobi.helper.IndexWorker.java

License:Open Source License

@SuppressWarnings("unchecked")
private void indexChunks(int batchSize) throws CustomResponseException, DAOException, IOException {
    Session session = HibernateUtil.getSession();
    List<Object> objectsToIndex = searchService.getAll(this.indexedObjects, batchSize);
    indexObjects(objectsToIndex);/*from  w w w.  j  a v  a2s.  co m*/
    session.clear();
}

From source file:de.unisb.cs.st.javalanche.mutation.results.persistence.QueryManager.java

License:Open Source License

public static void updateMutations(List<Mutation> results) {
    logger.info("Storing results for " + results.size() + " mutations");
    Session session = openSession();
    Transaction tx = session.beginTransaction();
    int saved = 1;
    for (Mutation mutation : results) {
        Mutation mutationFromDB = (Mutation) session.get(Mutation.class, mutation.getId());
        if (mutationFromDB.getMutationResult() != null) {
            logger.warn("Mutation already has a test result - not storing the given result");
            logger.warn("Mutation:" + mutationFromDB);
            logger.warn("Result (that is not stored): " + mutation);
            session.setReadOnly(mutationFromDB, true);
            session.close();// w  ww. j a va  2 s .c  om
            break;
        } else {
            session.save(mutation.getMutationResult());
            logger.debug("Setting result for mutation " + mutationFromDB.getId());
            mutationFromDB.setMutationResult(mutation.getMutationResult());
            saved++;
        }
        if (saved % 20 == 0) { // 20, same as the JDBC batch size
            // flush a batch of inserts and release memory:
            // see
            // http://www.hibernate.org/hib_docs/reference/en/html/batch.html
            session.flush();
            session.clear();
        }
    }
    if (session.isOpen()) {
        tx.commit();
        session.close();
        logger.info("Succesfully stored results for " + results.size() + " mutations");
    }
}