Example usage for javax.persistence EntityManager createQuery

List of usage examples for javax.persistence EntityManager createQuery

Introduction

In this page you can find the example usage for javax.persistence EntityManager createQuery.

Prototype

public Query createQuery(CriteriaDelete deleteQuery);

Source Link

Document

Create an instance of Query for executing a criteria delete query.

Usage

From source file:de.iai.ilcd.model.dao.ProcessDao.java

/**
 * Get query for list or count of processes which have provided flow as in- or output exchange flow
 * //from   ww w.j a va 2s  . c om
 * @param flow
 *            flow to get processes for
 * @param direction
 *            direction of process
 * @param count
 *            flag to indicate if count query shall be created
 * @return query for list or count of processes which have provided flow as in- or output exchange flow
 */
private Query getProcessesForExchangeFlowQuery(String flowUuid, ExchangeDirection direction, boolean count) {
    if (flowUuid == null) {
        throw new IllegalArgumentException("Flow must not be null!");
    }
    if (direction == null) {
        throw new IllegalArgumentException("Direction must not be null!");
    }
    EntityManager em = PersistenceUtil.getEntityManager();

    StringBuilder sb = new StringBuilder();
    sb.append("SELECT ");

    if (count) {
        sb.append("COUNT(DISTINCT p)");
    } else {
        sb.append("DISTINCT p");
    }

    sb.append(
            " FROM Process p LEFT JOIN p.exchanges e WHERE e.flow.uuid.uuid=:uuid AND e.exchangeDirection=:dir");

    Query q = em.createQuery(sb.toString());

    q.setParameter("uuid", flowUuid);
    q.setParameter("dir", direction);

    return q;

}

From source file:com.adeptj.modules.data.jpa.core.AbstractJpaRepository.java

/**
 * {@inheritDoc}/*from  ww w  .j a v  a2  s.  c  o  m*/
 */
@Override
public <T extends BaseEntity> int updateByCriteria(UpdateCriteria<T> criteria) {
    EntityManager em = JpaUtil.createEntityManager(this.getEntityManagerFactory());
    try {
        em.getTransaction().begin();
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaUpdate<T> cu = cb.createCriteriaUpdate(criteria.getEntity());
        criteria.getUpdateAttributes().forEach(cu::set);
        Root<T> root = cu.from(criteria.getEntity());
        int rowsUpdated = em
                .createQuery(cu.where(cb.and(Predicates.from(criteria.getCriteriaAttributes(), cb, root))))
                .executeUpdate();
        em.getTransaction().commit();
        LOGGER.debug("No. of rows updated: {}", rowsUpdated);
        return rowsUpdated;
    } catch (Exception ex) { // NOSONAR
        Transactions.markRollback(em);
        throw new JpaException(ex);
    } finally {
        Transactions.rollback(em);
        JpaUtil.closeEntityManager(em);
    }
}

From source file:com.xidu.framework.common.dao.impl.BaseDaoImpl.java

/**
 * {@inheritDoc} overridden:/* w  ww .  java 2  s . c o  m*/
 * 
 * @Date : 2011-4-1
 * @see com.xidu.framework.common.dao.IBaseDao#removeByQueryAndVaParam(java.lang.String,
 *      java.lang.Object[])
 **/
@Override
public void removeByQueryAndVaParam(final String queryStr, final Object... params) {
    getJpaTemplate().execute(new JpaCallback<Integer>() {

        @Override
        public Integer doInJpa(EntityManager em) throws PersistenceException {
            // TODO Auto-generated method stub
            Query removeQuery = em.createQuery(queryStr);
            prepareQueryParam(removeQuery, params);
            return removeQuery.executeUpdate();
        }

    });

}

From source file:com.xidu.framework.common.dao.impl.BaseDaoImpl.java

/**
 * {@inheritDoc} overridden://from w w  w.ja v  a  2s.  co  m
 * 
 * @Date : 2011-4-1
 * @see com.xidu.framework.common.dao.IBaseDao#removeByQueryAndMap(java.lang.String,
 *      java.util.Map)
 **/
@Override
public void removeByQueryAndMap(final String queryStr, final Map<String, ?> paraMap) {
    getJpaTemplate().execute(new JpaCallback<Integer>() {

        @Override
        public Integer doInJpa(EntityManager em) throws PersistenceException {
            // TODO Auto-generated method stub
            Query removeQuery = em.createQuery(queryStr);
            prepareQueryParam(removeQuery, paraMap);
            return removeQuery.executeUpdate();
        }

    });

}

From source file:com.xidu.framework.common.dao.impl.BaseDaoImpl.java

/**
 * {@inheritDoc} overridden://  w w w  .  ja va 2s  . c  o m
 * 
 * @Date : 2011-4-1
 * @see com.xidu.framework.common.dao.IBaseDao#updateByQUeryAndVaParam(java.lang.String,
 *      java.lang.Object[])
 **/
@Override
public void updateByQUeryAndVaParam(final String queryStr, final Object... params) {
    // TODO Auto-generated method stub
    getJpaTemplate().execute(new JpaCallback<Integer>() {

        @Override
        public Integer doInJpa(EntityManager em) throws PersistenceException {
            // TODO Auto-generated method stub
            Query updateQuery = em.createQuery(queryStr);
            prepareQueryParam(updateQuery, params);
            return updateQuery.executeUpdate();
        }

    });
}

From source file:com.xidu.framework.common.dao.impl.BaseDaoImpl.java

/**
 * {@inheritDoc} overridden:/*www .  j av  a2s . c o m*/
 * 
 * @Date : 2011-4-1
 * @see com.xidu.framework.common.dao.IBaseDao#updateByQueryAndMap(java.lang.String,
 *      java.util.Map)
 **/
@Override
public void updateByQueryAndMap(final String queryStr, final Map<String, ?> paraMap) {
    // TODO Auto-generated method stub
    getJpaTemplate().execute(new JpaCallback<Integer>() {

        @Override
        public Integer doInJpa(EntityManager em) throws PersistenceException {
            // TODO Auto-generated method stub
            Query updateQuery = em.createQuery(queryStr);
            prepareQueryParam(updateQuery, paraMap);
            return updateQuery.executeUpdate();
        }

    });
}

From source file:com.jada.admin.site.SiteLoader.java

public void remove() throws Exception {
    EntityManager em = JpaConnection.getInstance().getCurrentEntityManager();
    String sql = null;//  ww  w . j av  a2  s . c o m
    Query query = null;
    Iterator<?> iterator = null;

    sql = "delete from CreditCard where siteId = :siteId";
    query = em.createQuery(sql);
    query.setParameter("siteId", site.getSiteId());
    query.executeUpdate();

    sql = "from Report report where report.site.siteId = :siteId";
    query = em.createQuery(sql);
    query.setParameter("siteId", site.getSiteId());
    iterator = query.getResultList().iterator();
    while (iterator.hasNext()) {
        Report report = (Report) iterator.next();
        em.remove(report);
    }

    sql = "from IeProfileHeader ieProfileHeader where ieProfileHeader.site.siteId = :siteId";
    query = em.createQuery(sql);
    query.setParameter("siteId", site.getSiteId());
    iterator = query.getResultList().iterator();
    while (iterator.hasNext()) {
        IeProfileHeader ieProfileHeader = (IeProfileHeader) iterator.next();
        for (IeProfileDetail ieProfileDetail : ieProfileHeader.getIeProfileDetails()) {
            em.remove(ieProfileDetail);
        }
        em.remove(ieProfileHeader);
    }

    sql = "from Menu menu where menu.siteDomain in (select siteDomain from SiteDomain siteDomain where siteDomain.site.siteId = :siteId)";
    query = em.createQuery(sql);
    query.setParameter("siteId", site.getSiteId());
    iterator = query.getResultList().iterator();
    while (iterator.hasNext()) {
        Menu menu = (Menu) iterator.next();
        menu.setMenuLanguage(null);
        for (MenuLanguage menuLanguage : menu.getMenuLanguages()) {
            em.remove(menuLanguage);
        }
        em.remove(menu);
    }

    sql = "from Category category where category.site.siteId = :siteId)";
    query = em.createQuery(sql);
    query.setParameter("siteId", site.getSiteId());
    iterator = query.getResultList().iterator();
    while (iterator.hasNext()) {
        Category category = (Category) iterator.next();
        category.setCategoryLanguage(null);
        for (CategoryLanguage categoryLanguage : category.getCategoryLanguages()) {
            em.remove(categoryLanguage);
        }
        em.remove(category);
    }

    sql = "delete from ProductClass productClass where productClass.site.siteId = :siteId)";
    query = em.createQuery(sql);
    query.setParameter("siteId", site.getSiteId());
    query.executeUpdate();

    sql = "delete from CustomerClass customerClass where customerClass.site.siteId = :siteId)";
    query = em.createQuery(sql);
    query.setParameter("siteId", site.getSiteId());
    query.executeUpdate();

    sql = "from ShippingRate shippingRate " + "where   shippingRate in ( " + "select   shippingRate "
            + "from      ShippingMethodRegionType shippingMethodRegionType "
            + "where   shippingMethodRegionType.shippingMethod.site.siteId = :siteId " + ")";
    query = em.createQuery(sql);
    query.setParameter("siteId", site.getSiteId());
    iterator = query.getResultList().iterator();
    while (iterator.hasNext()) {
        ShippingRate shippingRate = (ShippingRate) iterator.next();
        em.remove(shippingRate);
    }

    sql = "from ShippingMethod where siteId = :siteId";
    query = em.createQuery(sql);
    query.setParameter("siteId", site.getSiteId());
    iterator = query.getResultList().iterator();
    while (iterator.hasNext()) {
        ShippingMethod shippingMethod = (ShippingMethod) iterator.next();
        em.remove(shippingMethod.getShippingMethodLanguage());
        em.remove(shippingMethod);
    }

    sql = "from ShippingRegion where siteId = :siteId";
    query = em.createQuery(sql);
    query.setParameter("siteId", site.getSiteId());
    iterator = query.getResultList().iterator();
    while (iterator.hasNext()) {
        ShippingRegion shippingRegion = (ShippingRegion) iterator.next();
        em.remove(shippingRegion);
    }

    sql = "from ShippingType where siteId = :siteId";
    query = em.createQuery(sql);
    query.setParameter("siteId", site.getSiteId());
    iterator = query.getResultList().iterator();
    while (iterator.hasNext()) {
        ShippingType shippingType = (ShippingType) iterator.next();
        em.remove(shippingType);
    }

    sql = "from State where stateId in (select stateId from State state where state.country.site.siteId = :siteId)";
    query = em.createQuery(sql);
    query.setParameter("siteId", site.getSiteId());
    iterator = query.getResultList().iterator();
    while (iterator.hasNext()) {
        State state = (State) iterator.next();
        state.setCountry(null);
        em.remove(state);
    }

    sql = "from Country where siteId = :siteId";
    query = em.createQuery(sql);
    query.setParameter("siteId", site.getSiteId());
    iterator = query.getResultList().iterator();
    while (iterator.hasNext()) {
        Country country = (Country) iterator.next();
        em.remove(country);
    }
    site.setSiteCurrencyClassDefault(null);
    site.setSiteProfileClassDefault(null);

    for (SiteDomain siteDomain : site.getSiteDomains()) {
        siteDomain.setSiteProfileDefault(null);
        siteDomain.setSiteCurrencyDefault(null);
        siteDomain.setBaseCurrency(null);
        siteDomain.setSiteDomainLanguage(null);

        HomePage homePage = siteDomain.getHomePage();
        for (HomePageDetail homePageDetail : homePage.getHomePageDetails()) {
            em.remove(homePageDetail);
        }
        for (HomePageLanguage homePageLanguage : homePage.getHomePageLanguages()) {
            em.remove(homePageLanguage);
        }
        em.remove(homePage);
        siteDomain.setHomePage(null);

        Template template = siteDomain.getTemplate();
        em.remove(template);
        siteDomain.setTemplate(null);
    }

    sql = "from SiteProfile siteProfile where siteProfile.siteDomain.site.siteId = :siteId";
    query = em.createQuery(sql);
    query.setParameter("siteId", site.getSiteId());
    iterator = query.getResultList().iterator();
    while (iterator.hasNext()) {
        SiteProfile siteProfile = (SiteProfile) iterator.next();
        em.remove(siteProfile);
    }

    sql = "from SiteCurrency siteCurrency where siteCurrency.siteDomain.site.siteId = :siteId";
    query = em.createQuery(sql);
    query.setParameter("siteId", site.getSiteId());
    iterator = query.getResultList().iterator();
    while (iterator.hasNext()) {
        SiteCurrency siteCurrency = (SiteCurrency) iterator.next();
        em.remove(siteCurrency);
    }

    sql = "from SiteProfileClass siteProfileClass where siteProfileClass.site.siteId = :siteId";
    query = em.createQuery(sql);
    query.setParameter("siteId", site.getSiteId());
    iterator = query.getResultList().iterator();
    while (iterator.hasNext()) {
        SiteProfileClass siteProfileClass = (SiteProfileClass) iterator.next();
        em.remove(siteProfileClass);
    }

    sql = "from SiteCurrencyClass siteCurrencyClass where siteCurrencyClass.site.siteId = :siteId";
    query = em.createQuery(sql);
    query.setParameter("siteId", site.getSiteId());
    iterator = query.getResultList().iterator();
    while (iterator.hasNext()) {
        SiteCurrencyClass siteCurrencyClass = (SiteCurrencyClass) iterator.next();
        siteCurrencyClass.setCurrency(null);
        em.remove(siteCurrencyClass);
    }

    sql = "from Currency currency where currency.site.siteId = :siteId";
    query = em.createQuery(sql);
    query.setParameter("siteId", site.getSiteId());
    iterator = query.getResultList().iterator();
    while (iterator.hasNext()) {
        Currency currency = (Currency) iterator.next();
        em.remove(currency);
    }

    sql = "from CustomAttribute customAttribute where customAttribute.site.siteId = :siteId";
    query = em.createQuery(sql);
    query.setParameter("siteId", site.getSiteId());
    iterator = query.getResultList().iterator();
    while (iterator.hasNext()) {
        CustomAttribute customAttribute = (CustomAttribute) iterator.next();
        em.remove(customAttribute);
        CustomAttributeLanguage customAttributeLanguage = customAttribute.getCustomAttributeLanguage();
        customAttributeLanguage.setCustomAttribute(null);
        em.remove(customAttributeLanguage);
    }

    sql = "from SiteDomain siteDomain where siteDomain.site.siteId = :siteId";
    query = em.createQuery(sql);
    query.setParameter("siteId", site.getSiteId());
    iterator = query.getResultList().iterator();
    while (iterator.hasNext()) {
        SiteDomain siteDomain = (SiteDomain) iterator.next();
        for (SiteDomainLanguage siteDomainLanguage : siteDomain.getSiteDomainLanguages()) {
            em.remove(siteDomainLanguage);
        }
        em.remove(siteDomain);
    }
}

From source file:es.alvsanand.webpage.db.dao.DAOHelper.java

protected Query getQuery(EntityManager entityManager, String queryName, QueryBean queryBean) {
    StringBuffer queryString = new StringBuffer(queryName);

    Query q = null;// w  w w .  j  a  v a 2 s.c  om

    if (queryBean != null) {
        if (queryBean.getOrderBeans() != null) {
            for (int i = 0; i < queryBean.getOrderBeans().size(); i++) {
                OrderBean orderBean = queryBean.getOrderBeans().get(i);

                if (StringUtils.isEmpty(orderBean.getName())) {
                    continue;
                }

                if (i == 0) {
                    queryString.append(ORDERBY_SPQL_TEXT);
                }

                queryString.append(orderBean.getName());
                queryString.append((orderBean.isAscendingOrder()) ? ASC_SPQL_TEXT : DES_SPQL_TEXT);
                if (i + 1 < queryBean.getOrderBeans().size()) {
                    queryString.append(", ");
                }
            }
        }

        q = entityManager.createQuery(queryString.toString());

        if (queryBean.getLimit() > 0) {
            q.setMaxResults(queryBean.getLimit());
        }
        if (queryBean.getOffset() > 0) {
            q.setFirstResult(queryBean.getOffset());
        }
    } else {
        q = entityManager.createQuery(queryName);
    }

    return q;
}

From source file:org.jasig.portlet.blackboardvcportlet.dao.impl.BaseJpaDaoTest.java

/**
 * Deletes ALL entities from the database
 *//* w  w  w  . j a va  2 s .  c om*/
@After
public final void deleteAllEntities() {
    final EntityManager entityManager = getEntityManager();
    final EntityManagerFactory entityManagerFactory = entityManager.getEntityManagerFactory();
    final Metamodel metamodel = entityManagerFactory.getMetamodel();
    Set<EntityType<?>> entityTypes = new LinkedHashSet<EntityType<?>>(metamodel.getEntities());

    do {
        final Set<EntityType<?>> failedEntitieTypes = new HashSet<EntityType<?>>();

        for (final EntityType<?> entityType : entityTypes) {
            final String entityClassName = entityType.getBindableJavaType().getName();

            try {
                this.executeInTransaction(new Callable<Object>() {
                    @Override
                    public Object call() throws Exception {
                        logger.trace("Purging all: " + entityClassName);

                        final Query query = entityManager
                                .createQuery("SELECT e FROM " + entityClassName + " AS e");
                        final List<?> entities = query.getResultList();
                        logger.trace("Found " + entities.size() + " " + entityClassName + " to delete");
                        for (final Object entity : entities) {
                            entityManager.remove(entity);
                        }

                        return null;
                    }
                });
            } catch (DataIntegrityViolationException e) {
                logger.trace(
                        "Failed to delete " + entityClassName + ". Must be a dependency of another entity");
                failedEntitieTypes.add(entityType);
            }
        }

        entityTypes = failedEntitieTypes;
    } while (!entityTypes.isEmpty());

    //Reset all spring managed mocks after every test
    MockitoFactoryBean.resetAllMocks();
}

From source file:nl.b3p.kaartenbalie.service.requesthandler.WFSRequestHandler.java

private List<SpLayerSummary> getLayerSummaries(String[] layers, String serviceName) throws Exception {
    EntityManager em = MyEMFDatabase.getEntityManager(MyEMFDatabase.MAIN_EM);

    List<SpLayerSummary> eventualSPList = new ArrayList();
    for (int i = 0; i < layers.length; i++) {
        String layer = layers[i];

        boolean splitName = (serviceName == null || serviceName.isEmpty()) ? true : false;
        LayerSummary m = OGCCommunication.splitLayerWithoutNsFix(layer, splitName, serviceName, null);
        String abbr = m.getSpAbbr();
        String name = OGCCommunication.buildLayerNameWithoutSp(m);

        List matchingLayers = em
                .createQuery("from WfsLayer l where l.name = :name and l.wfsServiceProvider.abbr = :abbr")
                .setParameter("name", name).setParameter("abbr", abbr).getResultList();

        if (matchingLayers.isEmpty()) {
            /*//from www.  j  a v  a 2 s . com
             * XXX "or no rights" ?? No rights are checked...
             */
            log.error("layer not found: " + layer);
            throw new Exception(KBConfiguration.REQUEST_NORIGHTS_EXCEPTION + ": " + layer);
        }

        if (matchingLayers.size() > 1) {
            log.error("layers with duplicate names, name: " + layer);
            throw new Exception(KBConfiguration.GETMAP_EXCEPTION);
        }

        WfsLayer l = (WfsLayer) matchingLayers.get(0);
        SpLayerSummary layerInfo = new SpLayerSummary(l, "true");

        addToServerProviderList(eventualSPList, layerInfo, false);
    }

    return eventualSPList;
}