Example usage for org.hibernate FlushMode MANUAL

List of usage examples for org.hibernate FlushMode MANUAL

Introduction

In this page you can find the example usage for org.hibernate FlushMode MANUAL.

Prototype

FlushMode MANUAL

To view the source code for org.hibernate FlushMode MANUAL.

Click Source Link

Document

The Session is only ever flushed when Session#flush is explicitly called by the application.

Usage

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 {/*w  ww  .  j a v  a 2  s  .  c o  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:es.tid.fiware.iot.ac.pdp.PdpEndpoint.java

License:Apache License

@POST
@UnitOfWork(readOnly = true, transactional = false, cacheMode = CacheMode.GET, flushMode = FlushMode.MANUAL)
@Timed//w  w w. jav a2s . c o  m
public Response enforce(@Tenant String tenant, String xacmlRequest) {

    LOGGER.debug("Enforcing policies for tenant [{}]", tenant);
    LOGGER.trace("XACML Request: {}", xacmlRequest);

    PDP pdp = pdpFactory.get(tenant, extractSubjectIds(xacmlRequest));
    return Response.ok(pdp.evaluate(xacmlRequest)).build();
}

From source file:fr.mael.microrss.dao.impl.UserArticleDaoImpl.java

License:Open Source License

public void reindex() {
    FullTextSession searchSession = null;
    searchSession = Search.getFullTextSession(getSessionFactory().getCurrentSession());
    searchSession.setFlushMode(FlushMode.MANUAL);
    searchSession.setCacheMode(CacheMode.IGNORE);
    searchSession.purgeAll(UserArticle.class);
    manageResults(UserArticle.class, searchSession);
}

From source file:fr.mcc.ginco.dao.hibernate.CustomConceptAttributeTypeDAO.java

License:CeCILL license

@Override
public CustomConceptAttributeType update(CustomConceptAttributeType conceptAttributeType) {
    getCurrentSession().setFlushMode(FlushMode.MANUAL);
    CustomConceptAttributeType existingAttrByCode = this.getAttributeByCode(conceptAttributeType.getThesaurus(),
            conceptAttributeType.getCode());
    CustomConceptAttributeType existingAttrByValue = this
            .getAttributeByValue(conceptAttributeType.getThesaurus(), conceptAttributeType.getValue());
    boolean isUniqueCode = true;
    boolean isUniqueValue = true;
    if (existingAttrByCode != null
            && existingAttrByCode.getIdentifier() != conceptAttributeType.getIdentifier())
        isUniqueCode = false;/*from   w  w  w . j  a v a 2  s  .co  m*/
    if (existingAttrByValue != null
            && existingAttrByValue.getIdentifier() != conceptAttributeType.getIdentifier())
        isUniqueValue = false;
    if (isUniqueValue && isUniqueCode) {
        getCurrentSession().saveOrUpdate(conceptAttributeType);
        getCurrentSession().flush();
    } else {
        if (!isUniqueValue) {
            throw new BusinessException(
                    "Already existing custom attribute with value : " + conceptAttributeType.getValue(),
                    "already-existing-custom-attribute-value",
                    new Object[] { conceptAttributeType.getValue() });
        } else {
            throw new BusinessException(
                    "Already existing custom attribute with code : " + conceptAttributeType.getCode(),
                    "already-existing-custom-attribute-code", new Object[] { conceptAttributeType.getCode() });
        }
    }
    return conceptAttributeType;
}

From source file:fr.mcc.ginco.dao.hibernate.CustomTermAttributeTypeDAO.java

License:CeCILL license

@Override
public CustomTermAttributeType update(CustomTermAttributeType termAttributeType) {
    getCurrentSession().setFlushMode(FlushMode.MANUAL);
    CustomTermAttributeType existingAttrByCode = this.getAttributeByCode(termAttributeType.getThesaurus(),
            termAttributeType.getCode());
    CustomTermAttributeType existingAttrByValue = this.getAttributeByValue(termAttributeType.getThesaurus(),
            termAttributeType.getValue());
    boolean isUniqueCode = true;
    boolean isUniqueValue = true;
    if (existingAttrByCode != null && existingAttrByCode.getIdentifier() != termAttributeType.getIdentifier())
        isUniqueCode = false;/*from   w  w  w. j a va  2s . c  o m*/
    if (existingAttrByValue != null && existingAttrByValue.getIdentifier() != termAttributeType.getIdentifier())
        isUniqueValue = false;
    if (isUniqueValue && isUniqueCode) {
        getCurrentSession().saveOrUpdate(termAttributeType);
        getCurrentSession().flush();
    } else {
        if (!isUniqueValue) {
            throw new BusinessException(
                    "Already existing custom attribute with value: " + termAttributeType.getValue(),
                    "already-existing-custom-attribute-value", new Object[] { termAttributeType.getValue() });
        } else {
            throw new BusinessException(
                    "Already existing custom attribute with code: " + termAttributeType.getCode(),
                    "already-existing-custom-attribute-code", new Object[] { termAttributeType.getCode() });
        }

    }
    return termAttributeType;
}

From source file:gov.nih.nci.caarray.dao.HibernateIntegrationTestCleanUpUtility.java

License:BSD License

private static boolean doCleanUp(String deleteSql) {
    Transaction tx = null;//from ww  w  . ja va 2s .c  om
    boolean removed = false;
    Session s = null;
    try {
        s = getSession();
        s.setFlushMode(FlushMode.MANUAL);
        tx = s.beginTransaction();
        disableForeignKeyChecks(s);
        int deletedObjs = s.createQuery(deleteSql).executeUpdate();
        if (deletedObjs > 0) {
            removed = true;
        }
        s.flush();
        tx.commit();
    } catch (DAOException deleteException) {
        hibernateHelper.rollbackTransaction(tx);
        LOG.warn("Error cleaning up test objects.", deleteException);
    } catch (HibernateException he) {
        hibernateHelper.rollbackTransaction(tx);
        LOG.warn("Error cleaning up test objects.", he);
    } finally {
        s.close();
    }
    return removed;
}

From source file:gov.nih.nci.caarray.validation.UniqueConstraintValidator.java

License:BSD License

/**
 * {@inheritDoc}/*from w  w w.  ja  v  a  2s .  co  m*/
 */
@SuppressWarnings({ "PMD.CyclomaticComplexity", "PMD.ExcessiveMethodLength" })
public boolean isValid(final Object o) {
    UnfilteredCallback unfilteredCallback = new UnfilteredCallback() {
        public Object doUnfiltered(Session s) {
            FlushMode fm = s.getFlushMode();
            try {
                s.setFlushMode(FlushMode.MANUAL);
                Class<?> classWithConstraint = findClassDeclaringConstraint(
                        hibernateHelper.unwrapProxy(o).getClass());
                Criteria crit = s.createCriteria(classWithConstraint);
                ClassMetadata metadata = hibernateHelper.getSessionFactory()
                        .getClassMetadata(classWithConstraint);
                for (UniqueConstraintField field : uniqueConstraint.fields()) {
                    Object fieldVal = metadata.getPropertyValue(o, field.name(), EntityMode.POJO);
                    if (fieldVal == null) {
                        if (field.nullsEqual()) {
                            // nulls are equal, so add it to to criteria
                            crit.add(Restrictions.isNull(field.name()));
                        } else {
                            // nulls are never equal, so uniqueness is automatically satisfied
                            return true;
                        }
                    } else {
                        // special casing for entity-type properties - only include them in the criteria if they are
                        // already
                        // persistent
                        // otherwise, short-circuit the process and return true immediately since if the
                        // entity-type property
                        // is not persistent then it will be a new value and thus different from any currently in 
                        // the db, thus satisfying uniqueness
                        ClassMetadata fieldMetadata = hibernateHelper.getSessionFactory()
                                .getClassMetadata(hibernateHelper.unwrapProxy(fieldVal).getClass());
                        if (fieldMetadata == null
                                || fieldMetadata.getIdentifier(fieldVal, EntityMode.POJO) != null) {
                            crit.add(Restrictions.eq(field.name(),
                                    ReflectHelper.getGetter(o.getClass(), field.name()).get(o)));
                        } else {
                            return true;
                        }
                    }
                }
                // if object is already persistent, then add condition to exclude it matching itself
                Object id = metadata.getIdentifier(o, EntityMode.POJO);
                if (id != null) {
                    crit.add(Restrictions.ne(metadata.getIdentifierPropertyName(), id));
                }

                int numMatches = crit.list().size();
                return numMatches == 0;
            } finally {
                s.setFlushMode(fm);
            }
        }
    };
    return (Boolean) hibernateHelper.doUnfiltered(unfilteredCallback);

}

From source file:gov.nih.nci.firebird.commons.test.TestDataRemover.java

License:Open Source License

public void cleanUp(List<String> dataRemovalSqlStatements) {
    Transaction tx = null;//from   ww  w  . j  a  v a 2  s  .  c om
    Session session = null;
    try {
        session = openSession();
        session.setFlushMode(FlushMode.MANUAL);
        tx = session.beginTransaction();
        doCleanUp(session, dataRemovalSqlStatements);
        session.flush();
        tx.commit();
    } catch (HibernateException he) {
        handleException(tx, he, "Error deleting test data");
    } finally {
        if (session != null) {
            session.close();
        }
    }
}

From source file:gov.nih.nci.firebird.test.TestDataHandler.java

License:Open Source License

public void cleanUp() {
    Transaction tx = null;/* w  w w.j  a  v a  2  s  .  c  o  m*/
    Session session = null;
    try {
        session = openSession();
        session.setFlushMode(FlushMode.MANUAL);
        tx = session.beginTransaction();
        doCleanUp(session);
        session.flush();
        tx.commit();
    } catch (HibernateException he) {
        handleException(tx, he, "Error deleting test data");
    } finally {
        if (session != null) {
            session.close();
        }
    }
}

From source file:gov.nih.nci.indexgen.Indexer.java

License:BSD License

/**
 * Generates lucene documents//from   ww  w. jav a 2 s . c o m
 */
public void run() {

    System.out.println("Started " + entity.getEntityName());

    long start = System.currentTimeMillis();

    try {
        fullTextSession.setFlushMode(FlushMode.MANUAL);
        fullTextSession.setCacheMode(CacheMode.IGNORE);
        Transaction transaction = fullTextSession.beginTransaction();

        // Scrollable results will avoid loading too many objects in memory
        ScrollableResults results = fullTextSession.createQuery("from " + entity.getEntityName())
                .scroll(ScrollMode.FORWARD_ONLY);

        int i = 0;
        while (results.next()) {
            fullTextSession.index(results.get(0));
            if (++i % batchSize == 0)
                fullTextSession.clear();
        }

        transaction.commit();
    }

    finally {
        fullTextSession.close();
    }

    long end = System.currentTimeMillis();
    System.out.println("Completed " + entity.getEntityName() + " in " + (end - start) + " ms");
}