Example usage for org.hibernate FlushMode ALWAYS

List of usage examples for org.hibernate FlushMode ALWAYS

Introduction

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

Prototype

FlushMode ALWAYS

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

Click Source Link

Document

The Session is flushed before every query.

Usage

From source file:com.amalto.core.storage.hibernate.HibernateStorage.java

License:Open Source License

@SuppressWarnings("rawtypes")
@Override//from  w w w . j  a va 2s . c om
public void delete(Expression userQuery) {
    Session session = this.getCurrentSession();
    try {
        storageClassLoader.bind(Thread.currentThread());
        // Session session = factory.getCurrentSession();
        userQuery = userQuery.normalize(); // First do a normalize for correct optimization detection.
        // Check if optimized delete for one type (and no filter) is applicable
        if (userQuery instanceof Select) {
            Select select = (Select) userQuery;
            List<ComplexTypeMetadata> types = select.getTypes();
            if (types.size() == 1 && select.getCondition() == null) {
                FlushMode previousFlushMode = session.getFlushMode();
                try {
                    session.setFlushMode(FlushMode.ALWAYS); // Force Hibernate to actually send SQL query to
                                                            // database during delete.
                    ComplexTypeMetadata mainType = types.get(0);
                    TypeMapping mapping = mappingRepository.getMappingFromUser(mainType);
                    // Compute (and eventually sort) types to delete
                    List<ComplexTypeMetadata> typesToDelete;
                    MetadataRepository internalRepository = typeMappingRepository.getInternalRepository();
                    if (mapping instanceof ScatteredTypeMapping) {
                        MetadataVisitor<List<ComplexTypeMetadata>> transitiveClosure = new TypeTransitiveClosure();
                        List<ComplexTypeMetadata> typeClosure = mapping.getDatabase().accept(transitiveClosure);
                        typesToDelete = MetadataUtils.sortTypes(internalRepository, typeClosure);
                    } else {
                        Collection<ComplexTypeMetadata> subTypes = mapping.getDatabase().getSubTypes();
                        if (subTypes.isEmpty()) {
                            typesToDelete = Collections.singletonList(mapping.getDatabase());
                        } else {
                            typesToDelete = new ArrayList<ComplexTypeMetadata>(subTypes.size() + 1);
                            typesToDelete.add(mapping.getDatabase());
                            typesToDelete.addAll(subTypes);
                        }
                    }
                    Map<ComplexTypeMetadata, Map<String, List>> recordsToDeleteMap = new HashMap<ComplexTypeMetadata, Map<String, List>>();
                    for (ComplexTypeMetadata typeToDelete : typesToDelete) {
                        InboundReferences inboundReferences = new InboundReferences(typeToDelete);
                        Set<ReferenceFieldMetadata> references = internalRepository.accept(inboundReferences);
                        // Empty values from intermediate tables to this non instantiable type and unset inbound
                        // references
                        if (typeToDelete.equals(mainType)) {
                            for (ReferenceFieldMetadata reference : references) {
                                if (reference.isMany()) {
                                    // No need to check for mandatory collections of references since constraint
                                    // cannot be expressed in db schema
                                    String formattedTableName = tableResolver.getCollectionTable(reference);
                                    session.createSQLQuery("delete from " + formattedTableName).executeUpdate(); //$NON-NLS-1$
                                } else {
                                    String referenceTableName = tableResolver
                                            .get(reference.getContainingType());
                                    if (referenceTableName.startsWith("X_ANONYMOUS")) { //$NON-NLS-1$
                                        session.createSQLQuery("delete from " + referenceTableName) //$NON-NLS-1$
                                                .executeUpdate();
                                    }
                                }
                            }
                        } else {
                            for (ReferenceFieldMetadata reference : references) {
                                if (reference.getContainingType().equals(mainType)) {
                                    HashMap<String, List> fieldsCondition = new HashMap<>();
                                    if (reference.isMany()) {
                                        // No need to check for mandatory collections of references since constraint
                                        // cannot
                                        // be expressed in db schema
                                        String formattedTableName = tableResolver.getCollectionTable(reference);
                                        session.createSQLQuery("delete from " + formattedTableName) //$NON-NLS-1$
                                                .executeUpdate();
                                    } else {
                                        String referenceTableName = tableResolver
                                                .get(reference.getContainingType());
                                        if (reference.getReferencedField() instanceof CompoundFieldMetadata) {
                                            FieldMetadata[] fields = ((CompoundFieldMetadata) reference
                                                    .getReferencedField()).getFields();
                                            for (FieldMetadata field : fields) {
                                                List list = session.createSQLQuery("select " //$NON-NLS-1$
                                                        + tableResolver.get(field, reference.getName())
                                                        + " from " //$NON-NLS-1$
                                                        + referenceTableName).list();
                                                if (list == null || list.isEmpty()) {
                                                    continue;
                                                } else {
                                                    fieldsCondition.put(
                                                            tableResolver.get(reference.getReferencedField()),
                                                            list);
                                                }
                                            }
                                        } else {
                                            List list = session.createSQLQuery("select " //$NON-NLS-1$
                                                    + tableResolver.get(reference.getReferencedField(),
                                                            reference.getName())
                                                    + " from " + referenceTableName).list(); //$NON-NLS-1$
                                            if (list == null || list.isEmpty()) {
                                                continue;
                                            } else {
                                                fieldsCondition.put(
                                                        tableResolver.get(reference.getReferencedField()),
                                                        list);
                                            }
                                        }
                                        recordsToDeleteMap.put(typeToDelete, fieldsCondition);
                                    }
                                }
                            }
                        }
                    }
                    deleteData(mapping.getDatabase(), new HashMap<String, List>(), mapping);
                    for (Map.Entry<ComplexTypeMetadata, Map<String, List>> entry : recordsToDeleteMap
                            .entrySet()) {
                        // Empty values in type isMany=true reference
                        deleteData(entry.getKey(), entry.getValue(), mapping);
                    }
                } finally {
                    session.setFlushMode(previousFlushMode);
                }
                return;
            }
        }
        // Generic fall back for deletions (filter)
        if (userQuery instanceof Select) {
            ((Select) userQuery).setForUpdate(true);
        }
        Iterable<DataRecord> records = internalFetch(session, userQuery,
                Collections.<ResultsCallback>emptySet());
        for (DataRecord currentDataRecord : records) {
            ComplexTypeMetadata currentType = currentDataRecord.getType();
            List<ComplexTypeMetadata> types = new ArrayList<>();
            if (userQuery instanceof Select) {
                types.addAll(((Select) userQuery).getTypes());
            }
            if (types.isEmpty() || types.contains(currentType)) {
                TypeMapping mapping = mappingRepository.getMappingFromUser(currentType);
                if (mapping == null) {
                    throw new IllegalArgumentException(
                            "Type '" + currentType.getName() + "' does not have a database mapping."); //$NON-NLS-1$ //$NON-NLS-2$
                }
                Class<?> clazz = storageClassLoader.getClassFromType(mapping.getDatabase());

                Serializable idValue;
                Collection<FieldMetadata> keyFields = currentType.getKeyFields();
                if (keyFields.size() == 1) {
                    idValue = (Serializable) currentDataRecord.get(keyFields.iterator().next());
                } else {
                    List<Object> compositeIdValues = new LinkedList<Object>();
                    for (FieldMetadata keyField : keyFields) {
                        compositeIdValues.add(currentDataRecord.get(keyField));
                    }
                    idValue = ObjectDataRecordConverter.createCompositeId(storageClassLoader, clazz,
                            compositeIdValues);
                }

                Wrapper object = (Wrapper) session.get(clazz, idValue, LockOptions.READ);
                if (object != null) {
                    session.delete(object);
                } else {
                    LOGGER.warn("Instance of type '" + currentType.getName() + "' and ID '" + idValue.toString() //$NON-NLS-1$ //$NON-NLS-2$
                            + "' has already been deleted within same transaction."); //$NON-NLS-1$
                }
            }
        }
    } catch (ConstraintViolationException e) {
        throw new com.amalto.core.storage.exception.ConstraintViolationException(e);
    } catch (HibernateException e) {
        throw new RuntimeException(e);
    } finally {
        this.releaseSession();
        storageClassLoader.unbind(Thread.currentThread());
    }
}

From source file:com.astonish.dropwizard.routing.hibernate.RoutingUnitOfWorkApplicationListenerTest.java

License:Apache License

@Test
public void configuresTheSessionsFlushMode() throws Exception {
    prepareAppEvent("methodWithFlushModeAlwaysAnnotation");

    execute();//  ww w  . j av  a2s .  co m

    verify(session).setFlushMode(FlushMode.ALWAYS);
}

From source file:com.astonish.dropwizard.routing.hibernate.RoutingUnitOfWorkRequestDispatcherTest.java

License:Apache License

@Test
public void configuresTheSessionsFlushMode() throws Exception {
    when(unitOfWork.flushMode()).thenReturn(FlushMode.ALWAYS);

    dispatcher.dispatch(resource, context);

    verify(session).setFlushMode(FlushMode.ALWAYS);
}

From source file:com.booleanworks.kryptopterus.application.WebAppBootstrapper.java

License:Apache License

public void setupMandatoryData() {

    System.out.println("com.booleanworks.kryptopterus.application.WebAppBootstrapper.setupMandatoryData()");

    System.out.println("Bootstrap-CP0005");

    MainHibernateUtil mhu = MainHibernateUtil.getInstance();
    Session session = mhu.getNewSession(FlushMode.ALWAYS, CacheMode.IGNORE);

    System.out.println("Bootstrap-CP0010");

    AppUser adminUser = AppUser.QuickCreateNewAppUser("admin", "4dm1n", "mickael.lecabellec@booleaworks.com",
            session);/*  w  ww  .ja v  a 2 s  .  c o  m*/
    AppUser testUser = AppUser.QuickCreateNewAppUser("test001", "test001", "mickael.lecabellec@booleaworks.com",
            session);

    System.out.println("Bootstrap-CP0020");

    AppUserGroup adminRole = AppUserGroup.findOrCreateAppUserGroup("ROLE_ADMIN", session);
    AppUserGroup userRole = AppUserGroup.findOrCreateAppUserGroup("ROLE_USER", session);
    AppUserGroup testUserRole = AppUserGroup.findOrCreateAppUserGroup("ROLE_TESTUSER", session);
    AppUserGroup anonymousRole = AppUserGroup.findOrCreateAppUserGroup("ROLE_ANONYMOUS", session);

    System.out.println("Bootstrap-CP0030");

    AppUserGroupMembership.quickAddMember(adminRole, adminUser, session);
    AppUserGroupMembership.quickAddMember(userRole, adminUser, session);
    AppUserGroupMembership.quickAddMember(testUserRole, adminUser, session);

    AppUserGroupMembership.quickAddMember(userRole, testUser, session);
    AppUserGroupMembership.quickAddMember(testUserRole, testUser, session);

    System.out.println("Bootstrap-CP0040");

    AppActivityStatus.findOrCreate("Default status for not started activities", "NOT_STARTED", session);
    AppActivityStatus.findOrCreate("Default status for started activities", "STARTED", session);
    AppActivityStatus.findOrCreate("Default status for finished activities", "FINISHED", session);
    AppActivityStatusTransition.findOrCreate("NOT_STARTED", "STARTED", "ROLE_USER", session);
    AppActivityStatusTransition.findOrCreate("STARTED", "FINISHED", "ROLE_USER", session);

    mhu.closeSession(session);

}

From source file:com.booleanworks.kryptopterus.application.WebAppBootstrapper.java

License:Apache License

public void setupTestData() {
    System.out.println("com.booleanworks.kryptopterus.application.WebAppBootstrapper.setupTestData()");

    System.out.println("Bootstrap-CP0041");

    MainHibernateUtil mhu = MainHibernateUtil.getInstance();
    Session session = mhu.getNewSession(FlushMode.ALWAYS, CacheMode.IGNORE);

    Calendar c = Calendar.getInstance();
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");

    System.out.println("Bootstrap-CP0050");

    AppActivityStatus.findOrCreate("New activity from app bootstrap", "TESTSTATUS_NEW", session);
    AppActivityStatus.findOrCreate("Finished (bootstrapactivity", "TESTSTATUS_FINISHED", session);
    AppActivityStatusTransition.findOrCreate("TESTSTATUS_NEW", "TESTSTATUS_FINISHED", "ROLE_ADMIN", session);

    System.out.println("Bootstrap-CP0060");

    ArrayList<AppActivity> testActivities = new ArrayList<>();

    AppUserGroup testUserRole = AppUserGroup.findOrCreateAppUserGroup("ROLE_TESTUSER", session);

    AppUser adminUser = AppUser.findUserOrNull("admin", session);
    if (adminUser == null) {
        System.err.println("WARNING: mandatory data missing... rebuilding");
        this.setupMandatoryData();
    }/*  w w w  .  j  a  v  a  2 s. c o  m*/

    for (int ct1 = 0; ct1 < 30; ct1++) {

        Transaction transaction = mhu.beginTransaction(session, false);

        AppActivity newTestActivity = AppActivity.findOrCreateWithBusinessIdentifier(
                "Test activity " + simpleDateFormat.format(c.getTime()), "TESTDATA-" + ct1, "TESTSTATUS_NEW",
                session);

        newTestActivity.setAuthorizedForView(testUserRole);
        newTestActivity.setAuthorizedForModification(testUserRole);
        newTestActivity.setAuthorizedForDeletion(testUserRole);

        newTestActivity.setCreator(adminUser);
        newTestActivity.setLastEditor(adminUser);
        newTestActivity.setCreationDate(new Date());
        newTestActivity.setModificationDate(new Date());

        newTestActivity.setPlannedStart(new Date());
        newTestActivity.setPlannedEnd(new Date());

        mhu.saveOrUpdate(newTestActivity, session);

        newTestActivity.addProperty(new AppProperty("MARKER", "TESTDATA"), session);

        mhu.saveOrUpdate(newTestActivity, session);

        testActivities.add(newTestActivity);

        mhu.commitTransaction(session, transaction);

    }

    Random random = new Random();

    for (int ct2 = 0; ct2 < 10; ct2++) {

        Transaction transaction = mhu.beginTransaction(session, false);

        AppActivity a1 = testActivities.get(random.nextInt(testActivities.size()));
        AppActivity a2 = testActivities.get(random.nextInt(testActivities.size()));

        AppActivityRelation aar = new AppActivityRelation();

        aar.setAuthorizedForView(testUserRole);
        aar.setAuthorizedForModification(testUserRole);
        aar.setAuthorizedForDeletion(testUserRole);

        aar.setCreator(adminUser);
        aar.setLastEditor(adminUser);
        aar.setCreationDate(new Date());
        aar.setModificationDate(new Date());

        aar.setDisplayName("TESTDATA-TRANSITION-" + simpleDateFormat.format(c.getTime()) + "-" + ct2);

        mhu.saveOrUpdate(aar, session);

        aar.link(a1, a2, session);

        aar.addProperty(new AppProperty("MARKER", "TESTDATA"), session);

        mhu.saveOrUpdate(aar, session);

        mhu.commitTransaction(session, transaction);

    }

    mhu.closeSession(session);

}

From source file:com.booleanworks.kryptopterus.entities.AppActivityRelation.java

License:Apache License

@Deprecated
public void link(AppActivity first, AppActivity second) {
    Session session = MainHibernateUtil.getInstance().getNewSession(FlushMode.ALWAYS, CacheMode.IGNORE);

    this.link(first, second, session);

    session.flush();/*from   w w  w  .jav a  2  s  .com*/
    session.close();
}

From source file:com.github.jmnarloch.hstreams.internal.QueryDelegateTest.java

License:Apache License

@Test
public void testSetFlushMode() throws Exception {

    // given/* www  .  j  av  a 2 s .  c o  m*/
    final FlushMode flushMode = FlushMode.ALWAYS;

    // then
    verifyMethodCall(q -> q.setFlushMode(flushMode));
}

From source file:com.github.jmnarloch.hstreams.internal.SessionDelegateTest.java

License:Apache License

@Test
public void testSetFlushMode() throws Exception {

    // given/*  ww  w .  ja  v a 2  s. c o  m*/
    final FlushMode flushMode = FlushMode.ALWAYS;

    // then
    verifyMethodCall(s -> s.setFlushMode(flushMode));
}

From source file:com.heliosapm.aa4h.parser.XMLQueryParser.java

License:Apache License

/**
 * Initializes a Criteria Query./*from www.  java2s  .  com*/
 * Mandatory Attributes:<ul>
 * <li><b>name</b>: The unqualified class name driving the criteria query.</li>
 * </ul>
 * Optional Attributes:<ul>
 * <li><b>prefix</b>: The package name of the class driving the criteria query. If null, no package is assumed.</li>
 * <li><b>maxSize</b>: The maximum number of rows to return from the database.</li>
 * <li><b>fetchSize</b>: The number of rows to fetch when rows are requested. Usually not useful for AA4H.</li>
 * <li><b>cacheEnabled</b>: Enables or disables caching for the queried objects.</li>
 * <li><b>cacheMode</b>: The cache options for the queried objects.</li>
 * <li><b>flushMode</b>: The session flush options.</li>
 * <li><b>fetchMode</b>: The collection fetch options for the query.</li>
 * <li><b>lockMode</b>: The row lock options for the queried rows.</li>
 * <li><b>timeOut</b>: The query timeout option.</li>
 * <li><b>rowCountOnly</b>: Returns a count of the query rows only.</li>
 * </ul>
 * @param attrs The attributes of the processed node.
 * @return An appended or new CriteriaSpecification
 * @throws SAXException
 */
protected CriteriaSpecification processCriteria(Attributes attrs) throws SAXException {
    if (inDetached) {
        return criteriaStack.peek();
    }
    String name = attrs.getValue("name");
    String prefix = attrs.getValue("prefix");
    if (prefix != null) {
        className = prefix + "." + name;
    } else {
        className = name;
    }
    String maxSize = attrs.getValue("maxSize");
    String fetchSize = attrs.getValue("fetchSize");
    String firstResult = attrs.getValue("firstResult");
    String cacheEnabled = attrs.getValue("cacheEnabled");
    String cacheMode = attrs.getValue("cacheMode");
    String flushMode = attrs.getValue("flushMode");
    String fetchMode = attrs.getValue("fetchMode");
    String lockMode = attrs.getValue("lockMode");
    String timeOut = attrs.getValue("timeOut");
    String rowCountOnly = attrs.getValue("rowCountOnly");
    Criteria newCriteria = null;
    try {
        if (criteriaStack.size() == 0) {
            newCriteria = session.createCriteria(className);
        } else {
            newCriteria = ((Criteria) criteriaStack.peek()).createCriteria(className);
        }
        criteriaStack.push(newCriteria);
        if ("true".equalsIgnoreCase(rowCountOnly)) {
            newCriteria.setProjection(Projections.projectionList().add(Projections.rowCount())

            );
            setRowCountOnly(true);
        }
        if (maxSize != null && isRowCountOnly() == false) {
            newCriteria.setMaxResults(Integer.parseInt(maxSize));
        }
        if (fetchSize != null && isRowCountOnly() == false) {
            newCriteria.setFetchSize(Integer.parseInt(fetchSize));
        }
        if (firstResult != null && isRowCountOnly() == false) {
            newCriteria.setFirstResult(Integer.parseInt(firstResult));
        }
        if (timeOut != null) {
            newCriteria.setTimeout(Integer.parseInt(timeOut));
        }

        if ("true".equalsIgnoreCase(cacheEnabled)) {
            newCriteria.setCacheable(true);
        } else if ("false".equalsIgnoreCase(cacheEnabled)) {
            newCriteria.setCacheable(false);
        }
        if (fetchMode != null && fetchMode.length() > 0) {
            if ("JOIN".equalsIgnoreCase(fetchMode)) {
                newCriteria.setFetchMode(name, FetchMode.JOIN);
            } else if ("SELECT".equalsIgnoreCase(fetchMode)) {
                newCriteria.setFetchMode(name, FetchMode.SELECT);
            } else {
                newCriteria.setFetchMode(name, FetchMode.DEFAULT);
            }
        } else {
            newCriteria.setFetchMode(name, FetchMode.DEFAULT);
        }
        if (cacheMode != null && cacheMode.length() > 0) {
            if ("GET".equalsIgnoreCase(cacheMode)) {
                newCriteria.setCacheMode(CacheMode.GET);
            } else if ("IGNORE".equalsIgnoreCase(cacheMode)) {
                newCriteria.setCacheMode(CacheMode.IGNORE);
            } else if ("NORMAL".equalsIgnoreCase(cacheMode)) {
                newCriteria.setCacheMode(CacheMode.NORMAL);
            } else if ("PUT".equalsIgnoreCase(cacheMode)) {
                newCriteria.setCacheMode(CacheMode.PUT);
            } else if ("REFRESH".equalsIgnoreCase(cacheMode)) {
                newCriteria.setCacheMode(CacheMode.REFRESH);
            } else {
                newCriteria.setCacheMode(CacheMode.NORMAL);
            }
        }
        if (lockMode != null && lockMode.length() > 0) {
            if ("NONE".equalsIgnoreCase(lockMode)) {
                newCriteria.setLockMode(LockMode.NONE);
            } else if ("READ".equalsIgnoreCase(lockMode)) {
                newCriteria.setLockMode(LockMode.READ);
            } else if ("UPGRADE".equalsIgnoreCase(lockMode)) {
                newCriteria.setLockMode(LockMode.UPGRADE);
            } else if ("UPGRADE_NOWAIT".equalsIgnoreCase(lockMode)) {
                newCriteria.setLockMode(LockMode.UPGRADE_NOWAIT);
            } else if ("WRITE".equalsIgnoreCase(lockMode)) {
                newCriteria.setLockMode(LockMode.WRITE);
            } else {
                throw new SAXException("lockMode[" + lockMode + "] Not Recognized");
            }
        }
        if (flushMode != null && flushMode.length() > 0) {
            if ("ALWAYS".equalsIgnoreCase(flushMode)) {
                newCriteria.setFlushMode(FlushMode.ALWAYS);
            } else if ("AUTO".equalsIgnoreCase(flushMode)) {
                newCriteria.setFlushMode(FlushMode.AUTO);
            } else if ("COMMIT".equalsIgnoreCase(flushMode)) {
                newCriteria.setFlushMode(FlushMode.COMMIT);
            } else if ("NEVER".equalsIgnoreCase(flushMode)) {
                // NEVER is deprecated, so we won't throw an exception but we'll ignore it.
            } else {
                throw new SAXException("flushMode[" + flushMode + "] Not Recognized");
            }
        }
        return newCriteria;

    } catch (Exception e) {
        throw new SAXException("Unable to configure class " + className, e);
    }
}

From source file:com.jklas.search.HibernateHydrateTest.java

License:Open Source License

@Before
public void Setup() {
    session = sessionFactory.openSession();
    session.beginTransaction();
    session.setFlushMode(FlushMode.ALWAYS);
}