Example usage for org.hibernate Session setFlushMode

List of usage examples for org.hibernate Session setFlushMode

Introduction

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

Prototype

@Deprecated
void setFlushMode(FlushMode flushMode);

Source Link

Document

Set the flush mode for this session.

Usage

From source file:de.innovationgate.webgate.api.jdbc.WGDatabaseImpl.java

License:Open Source License

/**
 * @throws WGUnavailableException /*from   w  ww.j  a  v a  2 s . c  o m*/
 * @throws WGAPIException 
 * @see de.innovationgate.webgate.api.WGDatabaseCore#openSession(String,
 *      String)
 */
public WGUserAccess openSession(AuthenticationSession authSession, Object pwd, boolean master)
        throws WGAPIException {

    try {

        // Hibernate login
        Session session = _sessionBuilder.openSession();
        // Connection conn = session.connection();
        // conn.setAutoCommit(true); //Problematic with DBCP?
        session.setFlushMode(FlushMode.COMMIT);
        if (_saveIsolationActive) {
            session.setDefaultReadOnly(true);
        }
        getSessionStatus().setSession(session);

        if (!session.isOpen()) {
            throw new WGUnavailableException(_db, "Unable to connect to hibernate session");
        }

        // special handling if loadbalancing is enabled
        if (hasFeature(WGDatabase.FEATURE_LOADBALANCE)) {

            // set all connections to readonly except master sessions and if
            // update is in progress
            final boolean readOnly = (master ? false : !isUpdateInProgress(authSession.getDistinguishedName()));

            try {
                session.doWork(new Work() {

                    public void execute(Connection connection) throws SQLException {
                        connection.setReadOnly(readOnly);
                    }
                });
            } catch (HibernateException e) {
                throw new WGBackendException("Unable to set readonly flag on connection.", e);
            }
        }

        if (getTransactionMode() != WGSessionContext.TRANSACTION_MODE_MANUAL) {
            session.beginTransaction();
        }

        if (master) {
            // Master login always has manager access
            return new WGUserAccess(WGDatabase.MASTER_USERNAME, WGDatabase.ACCESSLEVEL_MANAGER);
        }

        // Determine access
        WGUserDetails userDetails;
        try {
            userDetails = _db.defaultBuildUserDetails(authSession);
        } catch (WGBackendException e) {
            try {
                closeSession();
            } catch (WGBackendException e1) {
                WGFactory.getLogger().error(e1);
            }
            throw e;
        }
        if (userDetails.getAccessLevel() <= WGDatabase.ACCESSLEVEL_NOACCESS) {
            try {
                closeSession();
            } catch (WGBackendException e) {
                WGFactory.getLogger().error(e);
            }
        }

        return userDetails;

    } catch (HibernateException e) {
        try {
            closeSession();
        } catch (WGBackendException e1) {
            WGFactory.getLogger().error(e1);
        }
        throw new WGUnavailableException(_db, "Error opening hibernate session", e);
    }

}

From source file:de.iteratec.iteraplan.businesslogic.exchange.elasticeam.IteraplanMetamodelAndModelLoader.java

License:Open Source License

@Override
public MetamodelAndModelContainer call() throws ElasticeamException {
    MetamodelAndModelContainer result = null;

    try {/*ww w.j  a v  a2s  .  c  o  m*/
        //Create a temporary user context to avoid errors
        createTempUserContext();

        //Open a new session
        Session session = SessionFactoryUtils.getSession(hibernateAccessor.getSessionFactory(),
                hibernateAccessor.getEntityInterceptor(), hibernateAccessor.getJdbcExceptionTranslator());
        session.setFlushMode(FlushMode.MANUAL);
        session.setCacheMode(CacheMode.GET);
        SessionHolder sessionHolder = null;

        try {
            hibernateAccessor.applyFlushMode(session, false);
            sessionHolder = new SessionHolder(session);
            TransactionSynchronizationManager.bindResource(hibernateAccessor.getSessionFactory(),
                    sessionHolder);
            Transaction t = hibernateAccessor.getSessionFactory().getCurrentSession().beginTransaction();
            try {

                //Once the session has been opened, trigger the actual model and data loading in the superclass
                result = super.call();

                //After model and data have been loaded, close the session.
                t.commit();
            } catch (HibernateException e) {
                t.rollback();
                throw new ElasticeamException(ElasticeamException.GENERAL_ERROR,
                        "IteraQl model and data could not be loaded in iteraplan due to an exception in hibernate: \n "
                                + e);
            }
        } finally {
            SessionFactoryUtils.closeSession(sessionHolder.getSession());
            TransactionSynchronizationManager.unbindResource(hibernateAccessor.getSessionFactory());
        }

        //Remove the temporary user context
        UserContext.detachCurrentUserContext();

    } catch (Exception ex) {
        LOGGER.error("IteraQl model and data loading failed", ex);
        throw new ElasticeamException(ElasticeamException.GENERAL_ERROR,
                "IteraQl model and data loading failed: \n" + ex, ex);
    }
    return result;
}

From source file:de.iteratec.iteraplan.businesslogic.exchange.elasticmi.IteraplanMiLoadTask.java

License:Open Source License

@Override
public SimpleM3C call() {

    SimpleM3C result = null;// w  ww  .j  a v  a 2 s .c om
    if (UserContext.getCurrentUserContext() != null) {
        try {
            result = super.call();
        } catch (Exception ex) {
            LOGGER.error("IteraQl model and data loading failed", ex);
            throw new ElasticMiException(ElasticMiException.GENERAL_ERROR,
                    "IteraQl model and data loading failed: \n" + ex, ex);
        }
    } else {
        try {
            //Create a temporary user context to avoid errors
            createTempUserContext();

            //Open a new session
            Session session = SessionFactoryUtils.getSession(hibernateAccessor.getSessionFactory(),
                    hibernateAccessor.getEntityInterceptor(), hibernateAccessor.getJdbcExceptionTranslator());
            session.setFlushMode(FlushMode.MANUAL);
            session.setCacheMode(CacheMode.GET);
            SessionHolder sessionHolder = null;

            try {
                hibernateAccessor.applyFlushMode(session, false);
                sessionHolder = new SessionHolder(session);
                TransactionSynchronizationManager.bindResource(hibernateAccessor.getSessionFactory(),
                        sessionHolder);
                Transaction t = hibernateAccessor.getSessionFactory().getCurrentSession().beginTransaction();
                try {

                    //Once the session has been opened, trigger the actual model and data loading in the superclass
                    result = super.call();
                    //After model and data have been loaded, close the session.
                    t.commit();
                } catch (HibernateException e) {
                    t.rollback();
                    throw new ElasticMiException(ElasticMiException.GENERAL_ERROR,
                            "IteraQl model and data could not be loaded in iteraplan due to an exception in hibernate: \n "
                                    + e);
                }
            } finally {
                SessionFactoryUtils.closeSession(sessionHolder.getSession());
                TransactionSynchronizationManager.unbindResource(hibernateAccessor.getSessionFactory());
            }

        } catch (Exception ex) {
            LOGGER.error("IteraQl model and data loading failed", ex);
            throw new ElasticMiException(ElasticMiException.GENERAL_ERROR,
                    "IteraQl model and data loading failed: \n" + ex, ex);
        } finally {
            //Remove the temporary user context
            UserContext.detachCurrentUserContext();
        }
    }
    return result;
}

From source file:de.iteratec.iteraplan.persistence.dao.SearchDAOImpl.java

License:Open Source License

/** {@inheritDoc} */
public void createIndexes(Set<Class<?>> classList) {
    Session session = this.getSession();
    FullTextSession fullTextSession = getFullTextSession();

    session.setFlushMode(FlushMode.MANUAL); // Disable flush operations
    session.setCacheMode(CacheMode.IGNORE); // Disable second-level cache operations

    int batchSize = 100;

    // data is read from the database
    for (Class<?> bbClass : classList) {

        ScrollableResults results = session.createCriteria(bbClass).setFetchSize(batchSize)
                .scroll(ScrollMode.SCROLL_INSENSITIVE);

        LOGGER.info("Indexing " + bbClass.getSimpleName());
        int index = 0;
        while (results.next()) {
            index++;//from w w w. j  a v a2 s .  c  o  m
            // entities are indexed
            fullTextSession.index(results.get(0));
            if (index % batchSize == 0) {
                fullTextSession.flushToIndexes();
                fullTextSession.clear();
            }
        }
        results.close();
        LOGGER.info("Index for " + bbClass.getSimpleName() + " was created!");

    }
}

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

License:Apache License

/**
 *
 *
 * @return//from ww  w .j a va  2  s  .c  o m
 */
protected synchronized Session getSession() {
    Session session = HibernateUtil.getSessionFactory().openSession();
    if (!session.isOpen()) {
        session = HibernateUtil.getSessionFactory().openSession();
    }

    session.setFlushMode(FlushMode.MANUAL);
    ManagedSessionContext.bind(session);
    return session;
}

From source file:edu.duke.cabig.c3pr.grid.registrationservice.service.impl.C3PRRegistrationServiceImpl.java

License:BSD License

public List<PlannedNotification> getPlannedNotifications(String nciInstituteCode) {
    List<PlannedNotification> result;
    List<String> nciCodeList = new ArrayList<String>();
    nciCodeList.add(nciInstituteCode);/*  w  w w.  java  2 s  . c o  m*/

    SessionFactory sessionFactory = (SessionFactory) applicationContext.getBean("sessionFactory");
    Session session = sessionFactory.openSession(sessionFactory.getCurrentSession().connection());
    session.setFlushMode(FlushMode.MANUAL);
    result = new ArrayList<PlannedNotification>();
    try {
        //Query query =  session.createQuery("select p from PlannedNotification p, HealthcareSite o where p.id = o.plannedNotificationsInternal.id and o.nciInstituteCode = ?");
        Query query = session.createQuery(
                "select p from PlannedNotification p, HealthcareSite o where p.id = o.plannedNotificationsInternal.id and o.identifiersAssignedToOrganization.typeInternal='CTEP' and o.identifiersAssignedToOrganization.value in (:nciCodeList)")
                .setParameterList("nciCodeList", nciCodeList);
        Query query1 = session.createQuery(
                "select p from PlannedNotification p, HealthcareSite o where p.id = o.plannedNotificationsInternal.id and o.identifiersAssignedToOrganization.typeInternal='CTEP' and o.identifiersAssignedToOrganization.value="
                        + "'" + nciInstituteCode + "'");
        //          Query query = session.createQuery("Select p from PlannedNotification as p, o from HealthcareSite as o where p.id = o.plannedNotificationsInternal.id and" +
        //                "o.nci_institute_code in (:nciCodeList)").setParameterList("nciCodeList",nciCodeList);
        //          query.setEntity(0, nciCodeList);
        result = query.list();
    } catch (DataAccessResourceFailureException e) {
        logger.error(e.getMessage());
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (HibernateException e) {
        logger.error(e.getMessage());
    } catch (Exception e) {
        logger.error(e.getMessage());
    } finally {
        session.close();
    }
    return result;
    //result = organizationDao.getByNciIdentifier(configuration.get(Configuration.LOCAL_NCI_INSTITUTE_CODE)).get(0).getPlannedNotifications();
    //return result;
}

From source file:edu.duke.cabig.c3pr.infrastructure.interceptor.NotificationInterceptor.java

License:BSD License

/**
 * Gets the planned notifications for the list of sites that are passed in.
 * This method access the db using a new session from the hibernate session factory.
 * //  w  ww .j  a  v a 2 s  . co  m
 * @param hcsList the hcs list
 * @return the planned notifications
 */
public List<PlannedNotification> getPlannedNotifications(List<HealthcareSite> hcsList) {
    List<PlannedNotification> result;
    List<String> nciCodeList = new ArrayList<String>();
    for (HealthcareSite hcs : hcsList) {
        if (hcs != null) {
            nciCodeList.add(hcs.getPrimaryIdentifier());
        }
    }

    SessionFactory sessionFactory = (SessionFactory) applicationContext.getBean("sessionFactory");
    Session session = sessionFactory.openSession(sessionFactory.getCurrentSession().connection());
    session.setFlushMode(FlushMode.MANUAL);
    result = new ArrayList<PlannedNotification>();
    try {
        Query query = session.createQuery(
                "select p from PlannedNotification p, HealthcareSite o, Identifier i where p = any elements(o.plannedNotificationsInternal) and "
                        + "i = any elements(o.identifiersAssignedToOrganization) and i.primaryIndicator = 'true' and "
                        + "i.value in (:nciCodeList)")
                .setParameterList("nciCodeList", nciCodeList);

        result = query.list();
    } catch (DataAccessResourceFailureException e) {
        log.error(e.getMessage());
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (HibernateException e) {
        log.error(e.getMessage());
    } catch (Exception e) {
        log.error(e.getMessage());
    } finally {
        session.close();
    }
    return result;
}

From source file:edu.duke.cabig.c3pr.infrastructure.interceptor.NotificationInterceptor.java

License:BSD License

/**
 * Gets the planned notifications for the list of sites that are passed in.
 * This method access the db using a new session from the hibernate session factory.
 * /*from w  ww  .  j  a  v a2  s .c om*/
 * @param hcsList the hcs list
 * @return the planned notifications
 */
public List<PlannedNotification> getPlannedNotificationsForUpdateMasterSubject() {
    List<PlannedNotification> result;

    SessionFactory sessionFactory = (SessionFactory) applicationContext.getBean("sessionFactory");
    Session session = sessionFactory.openSession(sessionFactory.getCurrentSession().connection());
    session.setFlushMode(FlushMode.MANUAL);
    result = new ArrayList<PlannedNotification>();
    try {
        Query query = session.createQuery("from PlannedNotification p where p.eventName = :var")
                .setString("var", NotificationEventTypeEnum.MASTER_SUBJECT_UPDATED_EVENT.toString());

        result = query.list();
    } catch (DataAccessResourceFailureException e) {
        log.error(e.getMessage());
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (HibernateException e) {
        log.error(e.getMessage());
    } catch (Exception e) {
        log.error(e.getMessage());
    } finally {
        session.close();
    }
    return result;
}

From source file:edu.duke.cabig.c3pr.infrastructure.interceptor.NotificationInterceptor.java

License:BSD License

public List<PlannedNotification> getPlannedNotificationsForCorrespondence() {
    List<PlannedNotification> result;

    SessionFactory sessionFactory = (SessionFactory) applicationContext.getBean("sessionFactory");
    Session session = sessionFactory.openSession(sessionFactory.getCurrentSession().connection());
    session.setFlushMode(FlushMode.MANUAL);
    result = new ArrayList<PlannedNotification>();
    try {//from   w w  w  . ja  v a  2 s .co m
        Query query = session.createQuery(
                "from PlannedNotification p left join fetch p.userBasedRecipientInternal where p.eventName = :var")
                .setString("var", NotificationEventTypeEnum.CORRESPONDENCE_CREATED_OR_UPDATED_EVENT.toString());

        result = query.list().subList(0, 1);
    } catch (DataAccessResourceFailureException e) {
        log.error(e.getMessage());
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (HibernateException e) {
        log.error(e.getMessage());
    } catch (Exception e) {
        log.error(e.getMessage());
    } finally {
        session.close();
    }
    return result;
}

From source file:edu.duke.cabig.c3pr.service.impl.ScheduledNotificationServiceImpl.java

License:BSD License

public synchronized Integer saveScheduledNotification(PlannedNotification plannedNotification,
        String composedMessage, List<StudyOrganization> ssList, String eventId) {
    log.debug(this.getClass().getName() + ": Entering saveScheduledNotification()");
    ScheduledNotification scheduledNotification = null;

    //Creating a new session to save the scheduled notifications to avoid conflicts with the
    //CurrentSession (whose flush initiated this interceptor call in the first place).
    SessionFactory sessionFactory = (SessionFactory) applicationContext.getBean("notificationSessionFactory");
    Session session = sessionFactory.openSession();
    session.setFlushMode(FlushMode.COMMIT);
    try {/*from  ww  w .jav a  2  s. c  o  m*/
        session.update(plannedNotification);

        // for updating master subject notification event, planned notification is not associated to a healthcare site
        if (plannedNotification.getHealthcareSite() != null) {
            session.update(plannedNotification.getHealthcareSite());
        }
        //generating and saving the ScheduledNotification
        scheduledNotification = addScheduledNotification(plannedNotification, composedMessage, ssList, eventId);
        session.saveOrUpdate(plannedNotification);
        session.flush();
    } catch (Exception e) {
        log.error(e.getMessage());
    } finally {
        session.close();
    }
    log.debug(this.getClass().getName() + ": Exiting saveScheduledNotification()");
    if (scheduledNotification != null) {
        return scheduledNotification.getId();
    } else {
        log.error(this.getClass().getName()
                + "saveScheduledNotification(): ScheduledNotification was not saved successfully");
        return 0;
    }
}