Example usage for org.hibernate Query setFlushMode

List of usage examples for org.hibernate Query setFlushMode

Introduction

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

Prototype

@Override
    Query<R> setFlushMode(FlushModeType flushMode);

Source Link

Usage

From source file:org.cgiar.ccafs.marlo.data.dao.mysql.AbstractMarloDAO.java

License:Open Source License

/**
 * This method make a query that returns a not mapped object result from the model.
 * /*from w  w w .j  a  v  a 2s .c o  m*/
 * @param sqlQuery is a string representing an HQL query.
 */
public List<Map<String, Object>> findCustomQuery(String sqlQuery) {
    Query query = sessionFactory.getCurrentSession().createSQLQuery(sqlQuery);
    query.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE);
    query.setFlushMode(FlushMode.COMMIT);
    List<Map<String, Object>> result = query.list();

    return result;

}

From source file:org.cgiar.ccafs.marlo.data.dao.mysql.AbstractMarloDAO.java

License:Open Source License

protected List<T> findEveryone(Class<T> clazz) {
    Query query = sessionFactory.getCurrentSession().createQuery("from " + clazz.getName());
    query.setFlushMode(FlushMode.COMMIT);

    @SuppressWarnings("unchecked")
    List<T> list = query.list();
    return list;/* ww w  . java2 s. c om*/

}

From source file:org.cgiar.ccafs.marlo.data.dao.mysql.AbstractMarloDAO.java

License:Open Source License

/**
 * Allows clients to create the HibernateQuery and set parameters on it.
 * /*from www . java 2s .  co  m*/
 * @param clazz
 * @param hibernateQuery
 * @return
 */
protected T findSingleResult(Class<T> clazz, Query hibernateQuery) {
    hibernateQuery.setFlushMode(FlushMode.COMMIT);
    T object = clazz.cast(hibernateQuery.uniqueResult());
    return object;
}

From source file:org.cgiar.ccafs.marlo.data.dao.mysql.AbstractMarloDAO.java

License:Open Source License

/**
 * This method make a query that returns a single object result from the model.
 * This method was implemented in a generic way, so, the object to be returned will depend on how the method
 * is being called.//from   w  ww  .  ja  va2  s  .com
 * 
 * @param hibernateQuery is a string representing an HQL query.
 * @return a Object of <T>
 */
protected T findSingleResult(Class<T> clazz, String hibernateQuery) {
    Query query = sessionFactory.getCurrentSession().createQuery(hibernateQuery);
    query.setFlushMode(FlushMode.COMMIT);
    return this.findSingleResult(clazz, query);
}

From source file:org.codehaus.groovy.grails.orm.hibernate.metaclass.ExecuteQueryPersistentMethod.java

License:Apache License

@SuppressWarnings("rawtypes")
@Override/*  ww w .j a v  a  2s  .  c o  m*/
protected Object doInvokeInternal(Class clazz, String methodName, Closure additionalCriteria,
        Object[] arguments) {
    checkMethodSignature(clazz, arguments);

    final String query = arguments[0].toString();
    final Map queryMetaParams = extractQueryMetaParams(arguments);
    final List positionalParams = extractPositionalParams(arguments);
    final Map namedParams = extractNamedParams(arguments);

    return getHibernateTemplate().executeFind(new HibernateCallback<Object>() {
        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            Query q = session.createQuery(query);
            SimpleTypeConverter converter = new SimpleTypeConverter();
            // process paginate params
            if (queryMetaParams.containsKey(GrailsHibernateUtil.ARGUMENT_MAX)) {
                Integer maxParam = converter.convertIfNecessary(
                        queryMetaParams.get(GrailsHibernateUtil.ARGUMENT_MAX), Integer.class);
                q.setMaxResults(maxParam.intValue());
            }
            if (queryMetaParams.containsKey(GrailsHibernateUtil.ARGUMENT_OFFSET)) {
                Integer offsetParam = converter.convertIfNecessary(
                        queryMetaParams.get(GrailsHibernateUtil.ARGUMENT_OFFSET), Integer.class);
                q.setFirstResult(offsetParam.intValue());
            }
            if (queryMetaParams.containsKey(GrailsHibernateUtil.ARGUMENT_CACHE)) {
                q.setCacheable(
                        ((Boolean) queryMetaParams.get(GrailsHibernateUtil.ARGUMENT_CACHE)).booleanValue());
            }
            if (queryMetaParams.containsKey(GrailsHibernateUtil.ARGUMENT_FETCH_SIZE)) {
                Integer fetchSizeParam = converter.convertIfNecessary(
                        queryMetaParams.get(GrailsHibernateUtil.ARGUMENT_FETCH_SIZE), Integer.class);
                q.setFetchSize(fetchSizeParam.intValue());
            }
            if (queryMetaParams.containsKey(GrailsHibernateUtil.ARGUMENT_TIMEOUT)) {
                Integer timeoutParam = converter.convertIfNecessary(
                        queryMetaParams.get(GrailsHibernateUtil.ARGUMENT_TIMEOUT), Integer.class);
                q.setFetchSize(timeoutParam.intValue());
            }
            if (queryMetaParams.containsKey(GrailsHibernateUtil.ARGUMENT_READ_ONLY)) {
                q.setReadOnly(
                        ((Boolean) queryMetaParams.get(GrailsHibernateUtil.ARGUMENT_READ_ONLY)).booleanValue());
            }
            if (queryMetaParams.containsKey(GrailsHibernateUtil.ARGUMENT_FLUSH_MODE)) {
                q.setFlushMode((FlushMode) queryMetaParams.get(GrailsHibernateUtil.ARGUMENT_FLUSH_MODE));
            }
            // process positional HQL params
            int index = 0;
            for (Object parameter : positionalParams) {
                q.setParameter(index++, parameter instanceof CharSequence ? parameter.toString() : parameter);
            }

            // process named HQL params
            for (Object o : namedParams.entrySet()) {
                Map.Entry entry = (Map.Entry) o;
                if (!(entry.getKey() instanceof String)) {
                    throw new GrailsQueryException("Named parameter's name must be of type String");
                }
                String parameterName = (String) entry.getKey();
                if (!QUERY_META_PARAMS.contains(parameterName)) {
                    Object parameterValue = entry.getValue();
                    if (parameterValue == null) {
                        throw new IllegalArgumentException(
                                "Named parameter [" + entry.getKey() + "] value may not be null");
                    }
                    if (Collection.class.isAssignableFrom(parameterValue.getClass())) {
                        q.setParameterList(parameterName, (Collection) parameterValue);
                    } else if (parameterValue.getClass().isArray()) {
                        q.setParameterList(parameterName, (Object[]) parameterValue);
                    } else if (parameterValue instanceof CharSequence) {
                        q.setParameter(parameterName, parameterValue.toString());
                    } else {
                        q.setParameter(parameterName, parameterValue);
                    }
                }
            }
            return q.list();
        }
    });
}

From source file:org.openmrs.api.db.hibernate.HibernateOrderDAO.java

License:Mozilla Public License

@Override
public List<Object[]> getOrderFromDatabase(Order order, boolean isOrderADrugOrder) throws APIException {
    String sql = "SELECT patient_id, care_setting, concept_id FROM orders WHERE order_id = :orderId";

    if (isOrderADrugOrder) {
        sql = " SELECT o.patient_id, o.care_setting, o.concept_id, d.drug_inventory_id "
                + " FROM orders o, drug_order d WHERE o.order_id = d.order_id AND o.order_id = :orderId";
    }/*from   w  w w. j  ava  2s.co  m*/
    Query query = sessionFactory.getCurrentSession().createSQLQuery(sql);
    query.setParameter("orderId", order.getOrderId());

    //prevent hibernate from flushing before fetching the list
    query.setFlushMode(FlushMode.MANUAL);

    return query.list();
}

From source file:org.osaf.cosmo.dao.hibernate.ContentDaoImpl.java

License:Apache License

public Set<ContentItem> loadChildren(CollectionItem collection, Date timestamp) {
    try {/*from www . ja  va2 s .c o  m*/
        Set<ContentItem> children = new HashSet<ContentItem>();
        Query query = null;

        // use custom HQL query that will eager fetch all associations
        if (timestamp == null)
            query = getSession().getNamedQuery("contentItem.by.parent").setParameter("parent", collection);
        else
            query = getSession().getNamedQuery("contentItem.by.parent.timestamp")
                    .setParameter("parent", collection).setParameter("timestamp", timestamp);

        query.setFlushMode(FlushMode.MANUAL);
        List results = query.list();
        for (Iterator it = results.iterator(); it.hasNext();) {
            ContentItem content = (ContentItem) it.next();
            initializeItem(content);
            children.add(content);
        }

        return children;

    } catch (HibernateException e) {
        getSession().clear();
        throw convertHibernateAccessException(e);
    }
}

From source file:org.osaf.cosmo.dao.hibernate.ContentDaoImpl.java

License:Apache License

protected void checkForDuplicateICalUid(ICalendarItem item, CollectionItem parent) {

    // TODO: should icalUid be required?  Currrently its not and all
    // items created by the webui dont' have it.
    if (item.getIcalUid() == null)
        return;/*from  w w w.j ava 2 s .c o m*/

    // ignore modifications
    if (item instanceof NoteItem && ((NoteItem) item).getModifies() != null)
        return;

    // Lookup item by parent/icaluid
    Query hibQuery = null;
    if (item instanceof NoteItem)
        hibQuery = getSession().getNamedQuery("noteItemId.by.parent.icaluid")
                .setParameter("parentid", getBaseModelObject(parent).getId())
                .setParameter("icaluid", item.getIcalUid());
    else
        hibQuery = getSession().getNamedQuery("icalendarItem.by.parent.icaluid")
                .setParameter("parentid", getBaseModelObject(parent).getId())
                .setParameter("icaluid", item.getIcalUid());

    hibQuery.setFlushMode(FlushMode.MANUAL);

    Long itemId = (Long) hibQuery.uniqueResult();

    // if icaluid is in use throw exception
    if (itemId != null) {
        // If the note is new, then its a duplicate icaluid
        if (getBaseModelObject(item).getId() == -1) {
            Item dup = (Item) getSession().load(HibItem.class, itemId);
            throw new IcalUidInUseException(
                    "iCal uid" + item.getIcalUid() + " already in use for collection " + parent.getUid(),
                    item.getUid(), dup.getUid());
        }
        // If the note exists and there is another note with the same
        // icaluid, then its a duplicate icaluid
        if (getBaseModelObject(item).getId().equals(itemId)) {
            Item dup = (Item) getSession().load(HibItem.class, itemId);
            throw new IcalUidInUseException(
                    "iCal uid" + item.getIcalUid() + " already in use for collection " + parent.getUid(),
                    item.getUid(), dup.getUid());
        }
    }
}

From source file:org.osaf.cosmo.dao.hibernate.ItemDaoImpl.java

License:Apache License

public Ticket findTicket(String key) {
    if (key == null)
        throw new IllegalArgumentException("key cannot be null");

    try {//from www .j av a2  s .  com
        // prevent auto flushing when looking up ticket
        getSession().setFlushMode(FlushMode.MANUAL);
        Query hibQuery = getSession().getNamedQuery("ticket.by.key").setParameter("key", key);
        hibQuery.setCacheable(true);
        hibQuery.setFlushMode(FlushMode.MANUAL);
        return (Ticket) hibQuery.uniqueResult();
    } catch (HibernateException e) {
        getSession().clear();
        throw convertHibernateAccessException(e);
    }
}

From source file:org.osaf.cosmo.dao.hibernate.ItemDaoImpl.java

License:Apache License

protected Item findItemByParentAndName(Long userDbId, Long parentDbId, String name) {
    Query hibQuery = null;
    if (parentDbId != null) {
        hibQuery = getSession().getNamedQuery("item.by.ownerId.parentId.name").setParameter("ownerid", userDbId)
                .setParameter("parentid", parentDbId).setParameter("name", name);

    } else {/*from  w w  w.j  a  v  a 2s  .  c o  m*/
        hibQuery = getSession().getNamedQuery("item.by.ownerId.nullParent.name")
                .setParameter("ownerid", userDbId).setParameter("name", name);
    }
    hibQuery.setFlushMode(FlushMode.MANUAL);
    return (Item) hibQuery.uniqueResult();
}