Example usage for org.hibernate Session refresh

List of usage examples for org.hibernate Session refresh

Introduction

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

Prototype

void refresh(Object object);

Source Link

Document

Re-read the state of the given instance from the underlying database.

Usage

From source file:ca.mcgill.cs.swevo.qualyzer.util.HibernateUtil.java

License:Open Source License

/**
 * Refresh many objects.//from   ww w.  j  ava2  s .  co m
 * @param manager
 * @param objects
 */
public static void quietRefresh(HibernateDBManager manager, Object[] objects) {
    Transaction t = null;
    Session session = null;
    try {
        session = manager.openSession();
        t = session.beginTransaction();
        for (Object object : objects) {
            session.refresh(object);
        }
        t.commit();
    } catch (HibernateException e) {
        quietRollback(t);
    } finally {
        quietClose(session);
    }
}

From source file:ca.usask.gmcte.currimap.action.CourseManager.java

License:Open Source License

@SuppressWarnings("unchecked")
public boolean removeCourseOfferingFromCourse(int offeringId) {
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    session.beginTransaction();// w w w .  j av  a  2s  . c  o m
    try {
        CourseOffering offering = (CourseOffering) session.get(CourseOffering.class, offeringId);

        List<LinkCourseOfferingOutcome> linkOutcomes = (List<LinkCourseOfferingOutcome>) session
                .createQuery("FROM LinkCourseOfferingOutcome WHERE courseOffering.id=:offeringId")
                .setParameter("offeringId", offeringId).list();
        for (LinkCourseOfferingOutcome link : linkOutcomes) {
            List<LinkCourseOfferingOutcomeCharacteristic> chars = (List<LinkCourseOfferingOutcomeCharacteristic>) session
                    .createQuery(
                            "FROM LinkCourseOfferingOutcomeCharacteristic WHERE linkCourseOfferingOutcome.id =:linkId")
                    .setParameter("linkId", link.getId()).list();
            for (LinkCourseOfferingOutcomeCharacteristic c : chars) {
                session.delete(c);
            }
            session.delete(link);
        }
        List<LinkCourseOfferingAssessment> assessments = (List<LinkCourseOfferingAssessment>) session
                .createQuery("FROM LinkCourseOfferingAssessment WHERE courseOffering.id = :offeringId")
                .setParameter("offeringId", offeringId).list();
        for (LinkCourseOfferingAssessment assessment : assessments) {
            List<LinkCourseAssessmentFeedbackOption> exitsingOptions = session.createQuery(
                    "FROM LinkCourseAssessmentFeedbackOption WHERE linkCourseOfferingAssessment.id = :linkId")
                    .setParameter("linkId", assessment.getId()).list();
            for (LinkCourseAssessmentFeedbackOption toDelete : exitsingOptions) {
                session.delete(toDelete);
            }
            session.delete(assessment);
        }
        List<LinkCourseOfferingTeachingMethod> methods = (List<LinkCourseOfferingTeachingMethod>) session
                .createQuery("FROM LinkCourseOfferingTeachingMethod WHERE courseOffering.id = :offeringId")
                .setParameter("offeringId", offeringId).list();
        for (LinkCourseOfferingTeachingMethod method : methods) {
            session.delete(method);
        }
        List<LinkCourseOfferingInstructor> instructors = (List<LinkCourseOfferingInstructor>) session
                .createQuery("FROM LinkCourseOfferingInstructor WHERE courseOffering.id = :offeringId")
                .setParameter("offeringId", offeringId).list();
        for (LinkCourseOfferingInstructor instructor : instructors) {
            session.delete(instructor);
        }
        List<LinkAssessmentCourseOutcome> existingLinks = OutcomeManager.instance()
                .getLinkAssessmentCourseOutcomes(offeringId, session);
        for (LinkAssessmentCourseOutcome outcomeLink : existingLinks) {
            session.delete(outcomeLink);
        }
        List<LinkCourseOfferingContributionProgramOutcome> contributionLinks = ProgramManager.instance()
                .getCourseOfferingContributionLinks(offering, session);
        for (LinkCourseOfferingContributionProgramOutcome link : contributionLinks) {
            session.delete(link);
        }
        List<LinkCourseOutcomeProgramOutcome> links = ProgramManager.instance().getCourseOutcomeLinks(offering,
                session);
        for (LinkCourseOutcomeProgramOutcome link : links) {
            session.delete(link);
        }
        session.refresh(offering);

        session.delete(offering);
        session.getTransaction().commit();
        return true;
    } catch (Exception e) {
        HibernateUtil.logException(logger, e);
        try {
            session.getTransaction().rollback();
        } catch (Exception e2) {
            logger.error("Unable to roll back!", e2);
        }
        return false;
    }
}

From source file:ca.usask.gmcte.currimap.action.OutcomeManager.java

License:Open Source License

public boolean deleteCourseOfferingOutcome(int outcomeId, int courseOfferingId) {
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    session.beginTransaction();/*from ww w .j av a2 s. c  o m*/
    try {

        @SuppressWarnings("unchecked")
        List<LinkCourseOfferingOutcome> existing = (List<LinkCourseOfferingOutcome>) session.createQuery(
                "select l from LinkCourseOfferingOutcome l where l.courseOffering.id = :offeringId order by l.displayIndex")
                .setParameter("offeringId", courseOfferingId).list();

        LinkCourseOfferingOutcome toDelete = null;
        for (LinkCourseOfferingOutcome link : existing) {
            if (toDelete != null) {
                link.setDisplayIndex(link.getDisplayIndex() - 1);
                session.merge(link);
            }
            if (link.getCourseOutcome().getId() == outcomeId) {
                toDelete = link;
            }

        }

        if (toDelete != null) {
            Set<LinkCourseOfferingOutcomeCharacteristic> existingCharacteristics = toDelete
                    .getLinkCourseOfferingOutcomeCharacteristics();
            for (LinkCourseOfferingOutcomeCharacteristic linkToDelete : existingCharacteristics) {
                session.delete(linkToDelete);
            }
            List<LinkCourseOutcomeProgramOutcome> existingLinks = ProgramManager.instance()
                    .getProgramOutcomeLinksForCourseOutcome(courseOfferingId, outcomeId, session);
            for (LinkCourseOutcomeProgramOutcome programLinktoDelete : existingLinks) {
                session.delete(programLinktoDelete);
            }
            @SuppressWarnings("unchecked")
            List<LinkAssessmentCourseOutcome> existingAssessmentLinks = (List<LinkAssessmentCourseOutcome>) session
                    .createQuery(
                            "from LinkAssessmentCourseOutcome l where l.courseOffering.id=:courseOfferingId AND l.outcome.id=:outcomeId")
                    .setParameter("courseOfferingId", courseOfferingId).setParameter("outcomeId", outcomeId)
                    .list();
            for (LinkAssessmentCourseOutcome assessmentLinktoDelete : existingAssessmentLinks) {
                session.delete(assessmentLinktoDelete);
            }

            session.refresh(toDelete);
            session.delete(toDelete);
        }

        //   CourseOutcome toDelete = (CourseOutcome)session.get(CourseOutcome.class, outcomeId);
        //   session.delete(toDelete);
        session.getTransaction().commit();

        return true;
    } catch (Exception e) {
        HibernateUtil.logException(logger, e);
        try {
            session.getTransaction().rollback();
        } catch (Exception e2) {
            logger.error("Unable to roll back!", e2);
        }
        return false;
    }
}

From source file:com.bahadirakin.dao.impl.BaseHibernateDAO.java

License:Apache License

public void refresh(T entity) {
    if (entity == null) {
        throw new IllegalArgumentException("Entity Must not be null");
    }//w w  w  .j a va  2 s . c om

    try {
        Session session = this.getCurrentSession();
        Transaction transaction = session.beginTransaction();
        session.refresh(entity);
        transaction.commit();
    } catch (Exception e) {
        LOG.error("Error while refresh Entity. M: " + e.getMessage() + " C: " + e.getCause(), e);
    }
}

From source file:com.fiveamsolutions.nci.commons.audit.AuditLogInterceptor.java

License:Open Source License

/**
 * in case this is a collection which is lazy loaded by default
 * we want to make sure that we retrieve the collection items
 * before the session is closed.//from w ww  .  ja v  a 2 s .com
 * @param session the session to load the object
 * @param lazyLoadedObject the lazily loaded object
 */
protected void getLazyLoadedObjects(Session session, Object lazyLoadedObject) {
    if (lazyLoadedObject instanceof Collection) {
        for (Object item : (Collection<?>) lazyLoadedObject) {
            if (item instanceof PersistentClass) {
                session.refresh(item);
                break;
            }
        }
    }
}

From source file:com.floreantpos.model.dao.ShiftDAO.java

License:Open Source License

public void refresh(Shift shift) throws PosException {
    Session session = null;

    try {/*from  ww  w .  j av  a2s.com*/
        session = createNewSession();
        session.refresh(shift);
    } catch (Exception e) {
        throw new PosException("An error occured while refreshing Shift state.", e); //$NON-NLS-1$
    } finally {
        if (session != null) {
            try {
                session.close();
            } catch (Exception e) {
            }
        }
    }
}

From source file:com.floreantpos.model.dao.TerminalDAO.java

License:Open Source License

public void refresh(Terminal terminal) {
    Session session = null;

    try {//from w w  w. jav  a2s . co  m
        session = getSession();
        session.refresh(terminal);
    } finally {
        closeSession(session);
    }
}

From source file:com.floreantpos.model.dao._BaseRootDAO.java

License:Open Source License

/**
 * Used by the base DAO classes but here for your modification
 * Re-read the state of the given instance from the underlying database. It is inadvisable to use this to implement
 * long-running sessions that span many business tasks. This method is, however, useful in certain special circumstances.
 *///from w w w. j ava2  s. com
protected void refresh(Object obj, Session s) {
    s.refresh(obj);
}

From source file:com.jonschang.investing.stocks.service.YahooStockService.java

License:LGPL

protected Stock pullStockFromWebService(Stock stock) throws ServiceException {

    String urlStr = STOCK_EXCHANGE_URL.replace("{SYMBOL}", stock.getSymbol());
    try {/*from  w ww.j a  v a2  s.co m*/
        String content = null;
        if (stock.getSymbol().startsWith("^")) {
            content = "\"" + stock.getSymbol() + "\",\"INDEX\"";
        } else {
            URL url = new URL(urlStr);
            Logger.getLogger(this.getClass())
                    .info("Attempting to pulling stock information from Yahoo! at url " + url);
            content = FileUtils.readInputStream((InputStream) url.getContent());
            if (content == null) {
                throw new NotFoundException("no stock information found in \"" + content + "\" at url " + url);
            }
        }
        if (content != null) {

            String[] parts = content.trim().split("\",\"");

            String companyName = parts[0].replace("\"", "");
            String exchangeSymbol = parts[1].replace("\"", "");

            stock.setCompanyName(companyName);

            // if we couldn't find the stock under the symbol
            if (stock.getStockExchange() != null && stock.getStockExchange().getSymbol() != null
                    && stock.getStockExchange().getSymbol().compareTo(exchangeSymbol) != 0)
                throw new NotFoundException("the stock symbol requested \"" + stock.getSymbol()
                        + "\" was found under the exchange \"" + exchangeSymbol + "\", not \""
                        + stock.getStockExchange().getSymbol() + "\"");

            // if the exchange does not have a pkid, then attempt to use the StockExchangeService to discover it
            StockExchange pulledExchange = (StockExchange) Investing.instance().getExchangeServiceFactory()
                    .get(StockExchange.class).getExchange(exchangeSymbol);
            if (pulledExchange == null)
                throw new NotFoundException("the stock with symbol \"" + stock.getSymbol()
                        + "\" was found, but the exchange \"" + exchangeSymbol
                        + "\" was not.  do you need to add the exchange to StockExchangeService in exchange-service.xml?");
            else {
                //pulledExchange.getStocks().add(stock);
                stock.setStockExchange(pulledExchange);
            }

            // now we need to store the stock to the databased
            Session session = Investing.instance().getSessionFactory().getCurrentSession();
            session.beginTransaction();
            session.saveOrUpdate(stock);
            session.refresh(stock);
            session.getTransaction().commit();
        }
        Logger.getLogger(YahooStockService.class).info(content);

        pullSectorAndIndustryFromYahoo(stock);

        return stock;
    } catch (MalformedURLException mue) {
        throw new ServiceException("Parser threw a MalformedURLException looking for symbol "
                + stock.getSymbol() + " from Yahoo! at url " + urlStr, mue);
    } catch (IOException pe) {
        throw new ServiceException("Parser threw a IOException looking for symbol " + stock.getSymbol()
                + " from Yahoo! at url " + urlStr, pe);
    }
}

From source file:com.maydesk.base.util.PDBinding.java

License:Mozilla Public License

public boolean applyChanges() {
    // validate values
    boolean validationOK = true;
    for (IChangeSupportable component : changeData.keySet()) {
        component.setBorder(PDBorderFactory.getBorder());
        if (component instanceof TextComponent) {
            ((TextComponent) component).setToolTipText(""); // FIXME
        }// w ww.j  ava2 s .  c  o  m

        MyChangeData cd = changeData.get(component);
        if (cd == null)
            continue;

        // validation
        try {
            if (!(cd.soplet instanceof Enum))
                continue;
            Annotation sopletAnnotation = cd.soplet.getClass().getField(((Enum) cd.soplet).name())
                    .getAnnotations()[0];
            if (sopletAnnotation == null)
                continue;
            Method m = sopletAnnotation.getClass().getMethod("validator");
            if (m == null)
                continue;
            Enum<?> validator = (Enum<?>) m.invoke(sopletAnnotation);
            if (validator == null)
                continue;
            Method validate = validator.getClass().getMethod("validate", Object.class);
            validate.setAccessible(true);
            Object value = component.getValue();
            Boolean validationResult = (Boolean) validate.invoke(validator, value);
            if (Boolean.TRUE.equals(validationResult))
                continue;

            // validation error found
            component.setBorder(PDBorderFactory.getBorderError());
            if (component instanceof TextComponent) {
                Field field = validator.getDeclaringClass().getField(validator.name());
                Annotation ann = field.getAnnotations()[0];
                Method m2 = ann.getClass().getMethod("textEN");
                if (m2 != null) {
                    String errorMessage = (String) m2.invoke(ann);
                    ((TextComponent) component).setToolTipText(errorMessage);
                }
            }
            validationOK = false;
        } catch (NoSuchMethodException ex) {
            // no validator
        } catch (InvocationTargetException ex) {
            // no validator
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    if (!validationOK) {
        return false;
    }

    if (hasChanges()) {
        if (target instanceof MBaseWithTitle) {
            ((MBaseWithTitle) target).updateCachedValues();
        }
        Session session = PDHibernateFactory.getSession();
        if (target.getId() == 0) {
            session.save(target);
            if (dataLink != null) {
                session.flush();
                session.refresh(target);
                dataLink.setTargetId(target.getId());
                session.saveOrUpdate(dataLink);
            }
        } else {
            session.update(target);
        }
    }
    for (PDBinding childBinding : children) {
        childBinding.applyChanges();
    }
    resetChanges();
    if (saveDoneListener != null) {
        ActionEvent e = new ActionEvent(target, null);
        saveDoneListener.actionPerformed(e);
    }
    return true;
}