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:dao.AlbumsDAO.java

License:Open Source License

public Set<Album> getAlbumsByOwner(User owner) {
    Set<Album> res;/*from   ww w . ja va 2s. c  o m*/
    Session s = HibernateUtil.getSessionFactory().getCurrentSession();
    s.beginTransaction();

    s.refresh(owner);
    res = owner.getAlbums();
    for (Album a : res) {
        a.getName();
    }

    s.getTransaction().commit();
    HibernateUtil.getSessionFactory().close();
    return res;
}

From source file:DAO.GenericDaoJpaImpl.java

@Override
public T create(T t) throws ConstraintViolationException {
    Session session = em.unwrap(Session.class);

    try {/*www. j  a v a2 s. com*/
        em.getTransaction().begin();
        em.persist(t);
        em.getTransaction().commit();
    } catch (ConstraintViolationException ex) {
        throw ex;
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }
    }
    session.refresh(t);
    return t;
}

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

License:Open Source License

/**
 * Refresh process./*  ww w. jav a  2  s.  c o  m*/
 *
 * @param processID
 *            int
 */
public static void refreshProcess(int processID) {
    if (logger.isDebugEnabled()) {
        logger.debug("refreshing process with id " + processID);
    }
    try {
        Session session = HibernateUtilOld.getSessionFactory().openSession();
        if (session != null) {
            if (logger.isDebugEnabled()) {
                logger.debug("session is connected: " + session.isConnected());
                logger.debug("session is open: " + session.isOpen());
            }
        } else {
            logger.debug("session is null");
        }
        if ((session == null) || (!session.isOpen()) || (!session.isConnected())) {
            logger.debug("found no open session, don't refresh the process");
            if (session != null) {
                session.close();
                logger.debug("closed session");
            }
            return;
        }

        logger.debug("created a new session");
        Process o = (Process) session.get(Process.class, Integer.valueOf(processID));
        logger.debug("loaded process");
        session.refresh(o);
        logger.debug("refreshed process");
        session.close();
        logger.debug("closed session");
    } catch (Throwable e) {
        logger.error("cannot refresh process with id " + processID);
    }
}

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

License:Open Source License

/**
 * Refresh process - GUI./* ww  w  .  j  a v a 2s .c o  m*/
 *
 * @param processID
 *            int
 */
public static void refreshProcess_GUI(int processID) {
    if (logger.isDebugEnabled()) {
        logger.debug("refreshing process with id " + processID);
    }
    Session session = null;
    boolean needsClose = false;
    try {
        session = Helper.getHibernateSession();
        if (session == null || !session.isOpen() || !session.isConnected()) {
            logger.debug("session is closed, creating a new session");
            HibernateUtilOld.rebuildSessionFactory();
            session = HibernateUtilOld.getSessionFactory().openSession();
            needsClose = true;
        }
        Process o = (Process) session.get(Process.class, processID);
        logger.debug("loaded process");
        session.refresh(o);
        logger.debug("refreshed process");
        if (needsClose) {
            session.close();
            logger.debug("closed session");
        }
    } catch (Throwable e) {
        logger.error("cannot refresh process with id " + processID);
        if (needsClose) {
            session.close();
        }
    }
}

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

License:Open Source License

/**
 * Stop refresh./* www .  j  a  v a 2  s  . c om*/
 *
 * @param stepID
 *            task id
 */
public static void refreshStep(int stepID) {
    try {

        Session session = HibernateUtilOld.getSessionFactory().openSession();
        Task o = (Task) session.get(Task.class, stepID);
        session.refresh(o);
        session.close();
    } catch (Exception e) {
        logger.error("cannot refresh step with id " + stepID);
    }

}

From source file:de.uniwue.info6.database.map.daos.DaoTools.java

License:Apache License

/**
 *
 *
 * @param obj/*from www.  j  a v  a  2 s . c  o m*/
 */
protected synchronized void refresh(Object obj, Session session) {
    if (obj != null) {
        try {
            session.refresh(obj);
            session.update(obj);
        } catch (Exception e) {
            log.error("custom hibernate operation failed", e);
        }
    }
}

From source file:de.uzk.hki.da.action.ActionFactory.java

License:Open Source License

public void init() {
    setPreservationSystem(new PreservationSystem());
    getPreservationSystem().setId(1);//from w  w  w  .j  a va  2  s.c o m

    Session session = HibernateUtil.openSession();
    session.beginTransaction();
    session.refresh(preservationSystem);
    session.refresh(localNode);

    // Prevent lazy initialization issues. "Simulate" eager fetching in case 
    // it does not work with hibernate or jpa annotations
    Hibernate.initialize(getPreservationSystem().getConversion_policies());
    Hibernate.initialize(localNode.getCooperatingNodes());

    try {
        for (Node cn : localNode.getCooperatingNodes())
            cn.getId();
        //         for (Copy cp:localNode.getCopies());
    } catch (Exception e) {
        throw new RuntimeException("Unable to load cooperating nodes");
    }

    for (SubformatIdentificationStrategyPuidMapping sfiP : getSecondStageScanPolicies(session)) {
        fileFormatFacade.registerSubformatIdentificationStrategyPuidMapping(
                sfiP.getSubformatIdentificationStrategyName(), sfiP.getFormatPuid());
    }
    session.close();

    List<String> availableJobTypes = actionRegistry.getAvailableJobTypes();
    for (String actionName : availableJobTypes) {
        AbstractAction action = (AbstractAction) context.getBean(actionName);
        getActionStartStates().put(actionName, action.getStartStatus());
    }
}

From source file:de.uzk.hki.da.action.QueueConnector.java

License:Open Source License

/**
 * XXX locking synchronized, against itself and against get object need audit
 * //from   www  .j  a v  a  2  s .co m
 * IMPORTANT NOTE: Fetch objects from queue opens a new session.
 *
 * @param status the status
 * @param workingStatus typically a numerical value with three digits, stored as string.
 * working status third digit typically is 2 by convention.
 * @param node the node
 * @return the job
 * @author Daniel M. de Oliveira
 */
@SuppressWarnings({ "unchecked", "unused" })
public Job fetchJobFromQueue(String status, String workingStatus, Node node, PreservationSystem pSystem) {
    Session session = HibernateUtil.openSession();
    session.beginTransaction();
    logger.trace("Fetch job for node name " + node.getName());
    List<Job> joblist = null;
    try {
        session.refresh(node);
        session.refresh(pSystem);

        joblist = session.createQuery("SELECT j FROM Job j LEFT JOIN j.obj as o where j.status=?1 and "
                + "j.responsibleNodeName=?2 and o.object_state IN (100, 50, 40) and o.orig_name!=?3 order by j.date_modified asc ")
                .setParameter("1", status).setParameter("2", node.getName())
                .setParameter("3", "integrationTest").setCacheable(false).setMaxResults(1).list();

        if ((joblist == null) || (joblist.isEmpty())) {
            logger.trace("no job found for status {}.", status);
            session.close();
            return null;
        }

        Job job = joblist.get(0);

        // To circumvent lazy initialization issues
        for (ConversionInstruction ci : job.getConversion_instructions()) {
        }
        for (Job j : job.getChildren()) {
        }
        for (Package p : job.getObject().getPackages()) {
            for (DAFile f : p.getFiles()) {
            }
            for (Event e : p.getEvents()) {
            }
        }
        // -
        logger.debug("fetched job with id {} and status {}", job.getId(), job.getStatus());

        job.setStatus(workingStatus);
        job.setDate_modified(String.valueOf(new Date().getTime() / 1000L));
        session.merge(job);
        session.getTransaction().commit();
        session.close();

        logger.debug("fetched job with id {} and set status to {}", job.getId(), job.getStatus());

    } catch (Exception e) {
        session.close();
        logger.error("Caught error in fetchJobFromQueue");

        throw new RuntimeException(e.getMessage(), e);
    }
    return joblist.get(0);
}

From source file:de.uzk.hki.da.at.AcceptanceTest.java

License:Open Source License

private static void instantiateNode() {

    AbstractApplicationContext context = new FileSystemXmlApplicationContext(CONF_BEANS_XML);
    localNode = (Node) context.getBean("localNode");

    Session session = HibernateUtil.openSession();
    session.beginTransaction();//from   w  ww  .  ja  va 2 s.  c  om
    session.refresh(localNode);
    session.close();

    context.close();
}

From source file:de.uzk.hki.da.at.ATIntegrityCheck.java

License:Open Source License

private void setChecksumSecondaryCopy(Object object, String checksum, int minusDaysInPast) {
    Session session = HibernateUtil.openSession();
    session.beginTransaction();//from w w w.jav a2s  .c  om
    // replace proxies by real objects
    session.refresh(object);
    for (Copy rec : object.getLatestPackage().getCopies())
        rec.getId();

    // Simulate checksumming done by foreign nodes
    Copy copy = object.getLatestPackage().getCopies().iterator().next();

    copy.setChecksum(checksum);

    // set object to older creationdate than one day
    Calendar now = Calendar.getInstance();
    now.add(Calendar.DAY_OF_YEAR, minusDaysInPast);
    copy.setChecksumDate(now.getTime());

    session.update(copy);
    session.getTransaction().commit();
    session.close();
}