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:fr.amapj.service.services.authentification.PasswordManager.java

/**
 * Retrouve l'utilisateur avec ce resetPasswordSald
 * Retourne null si non trouv ou autre problme
 *///ww w. ja  va 2  s.  co m
@DbRead
public Utilisateur findUserWithResetPassword(String resetPasswordSalt) {
    EntityManager em = TransactionHelper.getEm();

    if ((resetPasswordSalt == null) || resetPasswordSalt.equals("")) {
        return null;
    }

    CriteriaBuilder cb = em.getCriteriaBuilder();

    CriteriaQuery<Utilisateur> cq = cb.createQuery(Utilisateur.class);
    Root<Utilisateur> root = cq.from(Utilisateur.class);

    // On ajoute la condition where 
    cq.where(cb.equal(root.get(Utilisateur.P.RESETPASSWORDSALT.prop()), resetPasswordSalt));

    List<Utilisateur> us = em.createQuery(cq).getResultList();
    if (us.size() == 0) {
        return null;
    }

    if (us.size() > 1) {
        logger.warn("Il y a plusieurs utilisateurs avec le salt " + resetPasswordSalt);
        return null;
    }

    Utilisateur u = us.get(0);

    if (u.getEtatUtilisateur() == EtatUtilisateur.INACTIF) {
        return null;
    }

    return u;
}

From source file:com.espirit.moddev.examples.uxbridge.newsdrilldown.test.CommandITCase.java

/**
 * Test cleanup./*from w  ww.  j a  v a  2 s .c  o m*/
 *
 * @throws Exception the exception
 */
@Test
public void testCleanup() throws Exception {

    assertEquals("DB not empty", 0, countArticles());
    assertEquals("DB not empty", 0, countCategories());
    assertEquals("DB not empty", 0, countMetaCategories());

    EntityManager em = emf.createEntityManager();

    String[] ids = new String[] { "489", "490" };
    int numberOfArticles = ids.length;

    // insert all items
    for (String id : ids) {
        // item should not be in the db
        Query query = em.createQuery(
                new StringBuilder().append("SELECT x FROM news x WHERE x.fs_id = ").append(id).toString());
        assertEquals(0, query.getResultList().size());

        // load content
        String content = getContent("src/test/resources/inbox/add/pressreleasesdetails_" + id + ".xml",
                "hibernate");
        // patch content - add createTime
        content = content.replace("<uxb_entity ",
                "<uxb_entity createTime=\"" + System.currentTimeMillis() + "\" ");
        // send content to jms broker
        template.sendBody("jms:topic:BUS_OUT", content);
    }
    // wait
    Thread.sleep(TimeOuts.LONG);

    assertEquals("not all news are present", numberOfArticles, countArticles());
    assertEquals("not all categories are present", 12, countCategories());
    assertEquals("not all metaCategories are present", 3, countMetaCategories());

    // Save the current time as expiredate
    long expiredate = System.currentTimeMillis();

    Thread.sleep(TimeOuts.SHORT);

    ids = new String[] { "490" };
    int numberOfNewArticles = ids.length;

    printMetaCats();
    // insert new items
    for (String id : ids) {
        // item should be in the db
        Query query = em.createQuery(
                new StringBuilder().append("SELECT x FROM news x WHERE x.fs_id = ").append(id).toString());
        assertEquals(1, query.getResultList().size());

        // load content
        String content = getContent("src/test/resources/inbox/add/pressreleasesdetails_" + id + ".xml",
                "hibernate");
        // patch content - add createTime
        content = content.replace("<uxb_entity ",
                "<uxb_entity createTime=\"" + System.currentTimeMillis() + "\" ");
        // send content to jms broker
        template.sendBody("jms:topic:BUS_OUT", content);
    }
    // wait
    Thread.sleep(TimeOuts.LONG);
    printMetaCats();

    assertEquals("not all news are present", numberOfArticles, countArticles());
    assertEquals("not all categories are present", 12, countCategories());
    assertEquals("not all metaCategories are present", 3, countMetaCategories());

    // now check, that old items are cleaned up
    for (String id : ids) {
        // load content
        String content = getContent("src/test/resources/inbox/cleanup/pressreleasesdetails.xml", "hibernate");
        // patch content - add createTime
        content = content.replace("<uxb_entity ", "<uxb_entity createTime=\"" + expiredate + "\" ");
        // send content to jms broker
        template.sendBody("jms:topic:BUS_OUT", content);
    }
    System.out.println("EXPIRE: " + expiredate);
    // wait
    Thread.sleep(TimeOuts.LONG);
    printMetaCats();

    // Check number of articles
    assertEquals("ups, there are too many news left in the db", numberOfNewArticles, countArticles());
    assertEquals("ups, there are too many categories left in the db", 6, countCategories());
    assertEquals("ups, there are too many metaCategories left in the db", 2, countMetaCategories());

    // Check newsdrilldown ids
    for (String id : ids) {
        // item should be in the db
        Query query = em.createQuery(
                new StringBuilder().append("SELECT x FROM news x WHERE x.fs_id = ").append(id).toString());
        assertEquals(1, query.getResultList().size());
    }

    // Check category ids
    ids = new String[] { "4160", "4161", "4163", "4164", "4165", "4166" };
    for (String id : ids) {
        // item should be in the db
        Query query = em.createQuery(
                new StringBuilder().append("SELECT x FROM category x WHERE x.fs_id = ").append(id).toString());
        assertEquals(1, query.getResultList().size());
    }

    // Check metaCategory ids
    ids = new String[] { "4096", "4097" };
    for (String id : ids) {
        // item should be in the db
        Query query = em.createQuery(new StringBuilder().append("SELECT x FROM metaCategory x WHERE x.fs_id = ")
                .append(id).toString());
        assertEquals(1, query.getResultList().size());
    }

    em.close();
}

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

/**
 * {@inheritDoc}// w  w w.  j  a va2  s .  c  o m
 */
@Override
public <T extends BaseEntity> int deleteAll(Class<T> entity) {
    EntityManager em = JpaUtil.createEntityManager(this.getEntityManagerFactory());
    try {
        em.getTransaction().begin();
        int rowsDeleted = em.createQuery(em.getCriteriaBuilder().createCriteriaDelete(entity)).executeUpdate();
        em.getTransaction().commit();
        LOGGER.debug("deleteAll: No. of rows deleted: [{}]", rowsDeleted);
        return rowsDeleted;
    } catch (Exception ex) { // NOSONAR
        Transactions.markRollback(em);
        throw new JpaException(ex);
    } finally {
        Transactions.rollback(em);
        JpaUtil.closeEntityManager(em);
    }
}

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

@Override
public Number count(String query, QueryType type) {
    EntityManager em = JpaUtil.createEntityManager(this.getEntityManagerFactory());
    try {//from   ww  w  . jav  a2s. c om
        switch (type) {
        case JPA:
            return (Number) em.createQuery(query).getSingleResult();
        case NATIVE:
            return (Number) em.createNativeQuery(query).getSingleResult();
        default:
            throw new IllegalStateException("Invalid QueryType!!");
        }
    } catch (Exception ex) { // NOSONAR
        throw new JpaException(ex);
    } finally {
        JpaUtil.closeEntityManager(em);
    }
}

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

public void loadCategory() throws Exception {
    EntityManager em = JpaConnection.getInstance().getCurrentEntityManager();
    String sql = "from Category where siteId = :siteId";
    Query query = em.createQuery(sql);
    query.setParameter("siteId", Constants.SITE_SYSTEM);
    Iterator<?> iterator = query.getResultList().iterator();
    while (iterator.hasNext()) {
        Category master = (Category) iterator.next();
        Category category = new Category();
        category.setCatNaturalKey(master.getCatNaturalKey());
        category.setSeqNum(master.getSeqNum());
        category.setPublished(master.getPublished());
        category.setSite(site);//from  w  ww  . j  a  v a 2 s  .c  om
        category.setCatId(null);
        category.setRecUpdateBy(userId);
        category.setRecUpdateDatetime(new Date(System.currentTimeMillis()));
        category.setRecCreateBy(userId);
        category.setRecCreateDatetime(new Date(System.currentTimeMillis()));
        category.setMenus(null);
        category.setCategoryLanguages(null);
        em.persist(category);
    }
}

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

/**
 * {@inheritDoc}//w  w w .ja v a  2s .  com
 */
@Override
public <T extends BaseEntity> List<T> findAll(Class<T> entity) {
    EntityManager em = JpaUtil.createEntityManager(this.getEntityManagerFactory());
    try {
        CriteriaQuery<T> cq = em.getCriteriaBuilder().createQuery(entity);
        return em.createQuery(cq.select(cq.from(entity))).getResultList();
    } catch (Exception ex) { // NOSONAR
        throw new JpaException(ex);
    } finally {
        JpaUtil.closeEntityManager(em);
    }
}

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

/**
 * {@inheritDoc}//from   w  w w.j  av  a  2s  .  c o  m
 */
@Override
public <T extends BaseEntity> List<T> findPaginatedRecords(Class<T> entity, int startPos, int maxResult) {
    EntityManager em = JpaUtil.createEntityManager(this.getEntityManagerFactory());
    try {
        CriteriaQuery<T> cq = em.getCriteriaBuilder().createQuery(entity);
        return em.createQuery(cq.select(cq.from(entity))).setFirstResult(startPos).setMaxResults(maxResult)
                .getResultList();
    } catch (Exception ex) { // NOSONAR
        throw new JpaException(ex);
    } finally {
        JpaUtil.closeEntityManager(em);
    }
}

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

public void loadTax() throws Exception {
    EntityManager em = JpaConnection.getInstance().getCurrentEntityManager();
    String sql = "from Tax where siteId = :siteId";
    Query query = em.createQuery(sql);
    query.setParameter("siteId", Constants.SITE_SYSTEM);
    Iterator<?> iterator = query.getResultList().iterator();
    while (iterator.hasNext()) {
        Tax master = (Tax) iterator.next();
        Tax tax = new Tax();
        Set<Country> countries = tax.getCountries();
        Set<State> states = tax.getStates();
        PropertyUtils.copyProperties(tax, master);
        tax.setSite(site);//w  w  w  . j av a  2 s. c o  m
        tax.setTaxId(null);
        tax.setRecUpdateBy(userId);
        tax.setRecUpdateDatetime(new Date(System.currentTimeMillis()));
        tax.setRecCreateBy(userId);
        tax.setRecCreateDatetime(new Date(System.currentTimeMillis()));
        tax.setTaxLanguages(null);
        tax.setCountries(countries);
        tax.setStates(states);
        Iterator<?> it = null;
        if (master.getCountries() != null) {
            it = master.getCountries().iterator();
            while (it.hasNext()) {
                Country mc = (Country) it.next();
                Country country = CountryDAO.loadByCountryName(site.getSiteId(), mc.getCountryName());
                tax.getCountries().add(country);
            }
        }
        if (master.getStates() != null) {
            it = master.getStates().iterator();
            while (it.hasNext()) {
                State mc = (State) it.next();
                State state = StateDAO.loadByStateName(site.getSiteId(), mc.getStateName());
                tax.getStates().add(state);
            }
        }
        em.persist(tax);
    }
}

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

public void loadMenu() throws Exception {
    EntityManager em = JpaConnection.getInstance().getCurrentEntityManager();
    String sql = "from Menu where siteId = :siteId order by menuSetName";
    Query query = em.createQuery(sql);
    query.setParameter("siteId", Constants.SITE_SYSTEM);
    Iterator<?> iterator = query.getResultList().iterator();
    while (iterator.hasNext()) {
        Menu master = (Menu) iterator.next();
        Menu menu = new Menu();
        PropertyUtils.copyProperties(menu, master);
        //           menu.setSite(site);
        menu.setMenuId(null);/*from   ww  w. j  av  a  2  s . c  o  m*/
        menu.setRecUpdateBy(userId);
        menu.setRecUpdateDatetime(new Date(System.currentTimeMillis()));
        menu.setRecCreateBy(userId);
        menu.setRecCreateDatetime(new Date(System.currentTimeMillis()));
        menu.setCategory(null);
        menu.setContent(null);
        menu.setItem(null);
        menu.setMenuLanguages(null);
        em.persist(menu);
    }
}

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

public void loadCurrency() throws Exception {
    EntityManager em = JpaConnection.getInstance().getCurrentEntityManager();
    String sql = "from Currency where siteId = :siteId order by currencyCode";
    Query query = em.createQuery(sql);
    query.setParameter("siteId", Constants.SITE_SYSTEM);
    Iterator<?> iterator = query.getResultList().iterator();
    while (iterator.hasNext()) {
        Currency master = (Currency) iterator.next();
        Currency currency = new Currency();
        PropertyUtils.copyProperties(currency, master);
        currency.setSite(site);/*from w w w.  j av  a 2 s.c om*/
        currency.setCurrencyId(null);
        currency.setRecUpdateBy(userId);
        currency.setRecUpdateDatetime(new Date(System.currentTimeMillis()));
        currency.setRecCreateBy(userId);
        currency.setRecCreateDatetime(new Date(System.currentTimeMillis()));
        em.persist(currency);
    }
}