Example usage for javax.persistence FlushModeType COMMIT

List of usage examples for javax.persistence FlushModeType COMMIT

Introduction

In this page you can find the example usage for javax.persistence FlushModeType COMMIT.

Prototype

FlushModeType COMMIT

To view the source code for javax.persistence FlushModeType COMMIT.

Click Source Link

Document

Flushing to occur at transaction commit.

Usage

From source file:com.expressui.core.dao.security.PermissionDao.java

/**
 * Finds permissions for a given role, entity type and field.
 *
 * @param role       the role to query//from   www. java  2 s. c  om
 * @param entityType the entity type to query
 * @param field      the field to query
 * @return found permissions
 */
public List<Permission> findByRoleEntityTypeAndField(Role role, String entityType, String field) {
    Query query = getEntityManager().createQuery("SELECT p FROM Permission p WHERE p.role = :role"
            + " AND p.targetType = :entityType AND p.field = :field");
    query.setParameter("role", role);
    query.setParameter("entityType", entityType);
    query.setParameter("field", field);

    query.setFlushMode(FlushModeType.COMMIT);

    return query.getResultList();
}

From source file:net.groupbuy.dao.impl.MemberRankDaoImpl.java

/**
 * ?//from w ww .  j  a v a 2 s .  c  o m
 * 
 * @param memberRank
 *            
 */
@Override
public void remove(MemberRank memberRank) {
    if (memberRank != null && !memberRank.getIsDefault()) {
        String jpql = "select product from Product product join product.memberPrice memberPrice where index(memberPrice) = :memberRank";
        List<Product> products = entityManager.createQuery(jpql, Product.class)
                .setFlushMode(FlushModeType.COMMIT).setParameter("memberRank", memberRank).getResultList();
        for (int i = 0; i < products.size(); i++) {
            Product product = products.get(i);
            product.getMemberPrice().remove(memberRank);
            if (i % 20 == 0) {
                super.flush();
                super.clear();
            }
        }
        super.remove(super.merge(memberRank));
    }
}

From source file:org.grails.datastore.mapping.transactions.DatastoreTransactionManager.java

@Override
protected void doBegin(Object o, TransactionDefinition definition) throws TransactionException {
    TransactionObject txObject = (TransactionObject) o;

    Session session = null;//from   www. j ava  2s  .  co  m
    try {
        session = txObject.getSessionHolder().getSession();

        if (definition.isReadOnly()) {
            // Just set to NEVER in case of a new Session for this transaction.
            session.setFlushMode(FlushModeType.COMMIT);
        }

        Transaction<?> tx;
        // Register transaction timeout.
        int timeout = determineTimeout(definition);
        if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) {
            tx = session.beginTransaction();
            tx.setTimeout(timeout);
        } else {
            // Open a plain Datastore transaction without specified timeout.
            tx = session.beginTransaction();
        }

        // Add the Datastore transaction to the session holder.
        txObject.setTransaction(tx);

        // Bind the session holder to the thread.
        if (txObject.isNewSessionHolder()) {
            TransactionSynchronizationManager.bindResource(getDatastore(), txObject.getSessionHolder());
        }
        txObject.getSessionHolder().setSynchronizedWithTransaction(true);
    } catch (Exception ex) {
        if (txObject.isNewSession()) {
            try {
                if (session != null && session.getTransaction().isActive()) {
                    session.getTransaction().rollback();
                }
            } catch (Throwable ex2) {
                logger.debug("Could not rollback Session after failed transaction begin", ex);
            } finally {
                DatastoreUtils.closeSession(session);
            }
        }
        throw new CannotCreateTransactionException("Could not open Datastore Session for transaction", ex);
    }
}

From source file:net.groupbuy.dao.impl.MemberDaoImpl.java

public List<Object[]> findPurchaseList(Date beginDate, Date endDate, Integer count) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Object[]> criteriaQuery = criteriaBuilder.createQuery(Object[].class);
    Root<Member> member = criteriaQuery.from(Member.class);
    Join<Product, Order> orders = member.join("orders");
    criteriaQuery.multiselect(member.get("id"), member.get("username"), member.get("email"),
            member.get("point"), member.get("amount"), member.get("balance"),
            criteriaBuilder.sum(orders.<BigDecimal>get("amountPaid")));
    Predicate restrictions = criteriaBuilder.conjunction();
    if (beginDate != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.greaterThanOrEqualTo(orders.<Date>get("createDate"), beginDate));
    }/*from   w  ww  . j a  v a  2 s  .co m*/
    if (endDate != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.lessThanOrEqualTo(orders.<Date>get("createDate"), endDate));
    }
    restrictions = criteriaBuilder.and(restrictions,
            criteriaBuilder.equal(orders.get("orderStatus"), OrderStatus.completed),
            criteriaBuilder.equal(orders.get("paymentStatus"), PaymentStatus.paid));
    criteriaQuery.where(restrictions);
    criteriaQuery.groupBy(member.get("id"), member.get("username"), member.get("email"), member.get("point"),
            member.get("amount"), member.get("balance"));
    criteriaQuery.orderBy(criteriaBuilder.desc(criteriaBuilder.sum(orders.<BigDecimal>get("amountPaid"))));
    TypedQuery<Object[]> query = entityManager.createQuery(criteriaQuery).setFlushMode(FlushModeType.COMMIT);
    if (count != null && count >= 0) {
        query.setMaxResults(count);
    }
    return query.getResultList();
}

From source file:net.groupbuy.dao.impl.ProductCategoryDaoImpl.java

/**
 * ?/*from w  w w .j av  a  2s.c o  m*/
 * 
 * @param productCategory
 *            ?
 */
@Override
public void remove(ProductCategory productCategory) {
    if (productCategory != null) {
        StringBuffer jpql = new StringBuffer("update Product product set ");
        for (int i = 0; i < Product.ATTRIBUTE_VALUE_PROPERTY_COUNT; i++) {
            String propertyName = Product.ATTRIBUTE_VALUE_PROPERTY_NAME_PREFIX + i;
            if (i == 0) {
                jpql.append("product." + propertyName + " = null");
            } else {
                jpql.append(", product." + propertyName + " = null");
            }
        }
        jpql.append(" where product.productCategory = :productCategory");
        entityManager.createQuery(jpql.toString()).setFlushMode(FlushModeType.COMMIT)
                .setParameter("productCategory", productCategory).executeUpdate();
        super.remove(productCategory);
    }
}

From source file:com.healthcit.cacure.dao.FormElementDao.java

/**
 * If the description list of a source element was changed,
 * this ensures that the description(s) of its associated LinkElements is up-to-date.
 *//* w ww. j  a va 2  s.c o m*/
public void updateAllFormElementsWithDescriptionChanged(FormElement formElement) {
    Iterator<Description> newDescriptionIterator = formElement.getDescriptionList().iterator();

    while (newDescriptionIterator.hasNext()) {
        Description newDescription = newDescriptionIterator.next();

        if (!newDescription.isNew()) {
            Query query = em.createNativeQuery(
                    "update form_element set description = :desc from description d where form_element.link_id=:uuid and form_element.description = d.source_description_text and d.id = :id");

            query.setParameter("desc", newDescription.getDescription());

            query.setParameter("uuid",
                    formElement.isLink() && !formElement.isExternalQuestion()
                            ? ((LinkElement) formElement).getSourceId()
                            : formElement.getUuid());

            query.setParameter("id", newDescription.getId());

            query.setFlushMode(FlushModeType.COMMIT);

            query.executeUpdate();
        }
    }
}

From source file:com.haulmont.cuba.core.sys.QueryImpl.java

private JpaQuery<T> getQuery() {
    if (query == null) {
        View view = views.isEmpty() ? null : views.get(0);

        if (isNative) {
            log.trace("Creating SQL query: {}", queryString);
            if (resultClass == null)
                query = (JpaQuery) emDelegate.createNativeQuery(queryString);
            else {
                if (!Entity.class.isAssignableFrom(resultClass)) {
                    throw new IllegalArgumentException(
                            "Non-entity result class for native query is not supported" + " by EclipseLink: "
                                    + resultClass);
                }//from www.j  av  a 2 s.  c  o m
                Class effectiveClass = metadata.getExtendedEntities().getEffectiveClass(resultClass);
                query = (JpaQuery) emDelegate.createNativeQuery(queryString, effectiveClass);
            }
        } else {
            log.trace("Creating JPQL query: {}", queryString);
            String s = transformQueryString();
            log.trace("Transformed JPQL query: {}", s);

            Class effectiveClass = getEffectiveResultClass();
            if (effectiveClass != null) {
                query = (JpaQuery) emDelegate.createQuery(s, effectiveClass);
            } else {
                query = (JpaQuery) emDelegate.createQuery(s);
            }
            if (view != null) {
                MetaClass metaClass = metadata.getClassNN(view.getEntityClass());
                if (!metadata.getTools().isCacheable(metaClass) || !singleResultExpected) {
                    query.setHint(QueryHints.REFRESH, HintValues.TRUE);
                    query.setHint(QueryHints.REFRESH_CASCADE, CascadePolicy.CascadeByMapping);
                }
            }
        }
        if (view != null && !view.loadPartialEntities()) {
            query.setFlushMode(FlushModeType.AUTO);
        } else {
            query.setFlushMode(FlushModeType.COMMIT);
        }

        boolean nullParam = false;
        for (Param param : params) {
            param.apply(query);
            if (param.value == null)
                nullParam = true;
        }

        addMacroParams(query);

        // disable SQL caching to support "is null" generation
        if (nullParam)
            query.setHint(QueryHints.PREPARE, HintValues.FALSE);

        // Set maxResults and firstResult only if the query is not by ID, otherwise EclipseLink does not select
        // nested collections in some cases
        if (maxResults != null && !singleResultExpected)
            query.setMaxResults(maxResults);
        if (firstResult != null && !singleResultExpected)
            query.setFirstResult(firstResult);

        if (lockMode != null)
            query.setLockMode(lockMode);

        for (int i = 0; i < views.size(); i++) {
            if (i == 0)
                fetchGroupMgr.setView(query, queryString, views.get(i), singleResultExpected);
            else
                fetchGroupMgr.addView(query, queryString, views.get(i), singleResultExpected);
        }
    }
    //noinspection unchecked
    return query;
}

From source file:com.zero.dao.impl.BaseDaoImpl.java

protected List<T> findList(CriteriaQuery<T> criteriaQuery, Integer first, Integer count, List<Filter> filters,
        List<Order> orders) {
    Assert.notNull(criteriaQuery);/*from ww w .jav a  2  s .c  o m*/
    Assert.notNull(criteriaQuery.getSelection());
    Assert.notEmpty(criteriaQuery.getRoots());

    addRestrictions(criteriaQuery, filters);
    TypedQuery<T> query = entityManager.createQuery(criteriaQuery).setFlushMode(FlushModeType.COMMIT);
    if (first != null) {
        query.setFirstResult(first);
    }
    if (count != null) {
        query.setMaxResults(count);
    }
    return query.getResultList();
}

From source file:net.groupbuy.dao.impl.ReviewDaoImpl.java

public boolean isReviewed(Member member, Product product) {
    if (member == null || product == null) {
        return false;
    }// w ww  . j ava  2s .com
    String jqpl = "select count(*) from Review review where review.member = :member and review.product = :product";
    Long count = entityManager.createQuery(jqpl, Long.class).setFlushMode(FlushModeType.COMMIT)
            .setParameter("member", member).setParameter("product", product).getSingleResult();
    return count > 0;
}

From source file:org.grails.datastore.mapping.engine.NativeEntryEntityPersister.java

@Override
protected void deleteEntity(PersistentEntity persistentEntity, Object obj) {
    if (obj == null) {
        return;/*ww w.  j  a  v  a 2  s  . c  o  m*/
    }

    EntityAccess entityAccess = createEntityAccess(persistentEntity, obj);
    PreDeleteEvent event = new PreDeleteEvent(session.getDatastore(), persistentEntity, entityAccess);
    publisher.publishEvent(event);
    if (event.isCancelled()) {
        return;
    }

    final K key = readIdentifierFromObject(obj);
    if (key == null) {
        return;
    }

    FlushModeType flushMode = session.getFlushMode();
    try {
        session.setFlushMode(FlushModeType.COMMIT);
        cascadeBeforeDelete(persistentEntity, entityAccess, key, obj);
        deleteEntry(getEntityFamily(), key, obj);
        cascadeAfterDelete(persistentEntity, entityAccess, key, obj);
    } finally {
        session.setFlushMode(flushMode);
    }

    firePostDeleteEvent(persistentEntity, entityAccess);
}