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:com.siberhus.ngai.core.CrudHelper.java

public final static Number countAll(EntityManager em, Class<?> entityClass) {
    if (em == null) {
        throw new IllegalArgumentException("EntityManager is null");
    }//from  ww w  . j  a  va 2  s  .  c o  m
    EntityInfo entityInfo = CrudHelper.getEntityInfo(entityClass);
    String jpql = "select count(*) from " + entityInfo.getEntityName();
    return (Number) em.createQuery(jpql).getSingleResult();
}

From source file:com.github.jinahya.persistence.ShadowTest.java

protected static List<Morton> MORTONS(final EntityManager manager, final int firstResult,
        final int maxResults) {

    final CriteriaBuilder builder = manager.getCriteriaBuilder();
    final CriteriaQuery<Morton> query = builder.createQuery(Morton.class);
    final Root<Morton> morton = query.from(Morton.class);

    query.select(morton).orderBy(builder.desc(morton.get(Morton_.id)));

    return manager.createQuery(query).setFirstResult(firstResult).setMaxResults(maxResults).getResultList();
}

From source file:entity.files.SYSFilesTools.java

/**
 * <code>putFile(String)</code> speichert eine Datei auf dem FTP Server ab und erstellt eine SYSFiles EntityBean. Die Methode geht dabei wie folgt vor:
 * <ol>// w ww  . jav  a2s.c  om
 * <li>Zuerst wird der MD5 der zu speichernden Datei berechnet.</li>
 * <li>Anhand dieser MD5 Signatur wird ermittelt, ob es schon einen entsprechenden Eintrag in der Datenbank gibt.
 * <ul>
 * <li>Wenn ja, dann wird einfach der PK zurckgegeben. Nochmal speichern braucht man das ja nicht. <b>RETURN</b></li>
 * <li>Wenn nicht, dann geht die Bearbeitung weiter.</li>
 * </ul>
 * <li>Erstellen einer SYSFiles EB</li>
 * <li>Senden der Datei an den FTP Server</li>
 * <li>Wenn die letzten beiden Schritte erfolgreich waren, dann wird die neue EB als Ergebnis zurck gegeben. null, bei Fehler.</li>
 * </ol>
 *
 * @param file File Objekt der zu speichernden Datei
 * @return EB der neuen Datei. null bei Fehler.
 */
private static SYSFiles putFile(EntityManager em, FileTransferClient ftp, File file) throws Exception {
    SYSFiles sysfile = null;

    String md5 = SYSTools.getMD5Checksum(file);
    Query query = em.createQuery("SELECT s FROM SYSFiles s WHERE s.md5 = :md5");
    query.setParameter("md5", md5);

    ArrayList<SYSFiles> alreadyExistingFiles = new ArrayList<SYSFiles>(query.getResultList());

    // Gibts die Datei schon ?
    if (alreadyExistingFiles.isEmpty()) { // nein, noch nicht
        sysfile = em.merge(new SYSFiles(file.getName(), md5, new Date(file.lastModified()), file.length(),
                OPDE.getLogin().getUser()));
        //            FileInputStream fis = new FileInputStream(file);
        ftp.uploadFile(file.getPath(), sysfile.getRemoteFilename());

        //            ftp.storeF.storeFile(file.getPath(),sysfile.getRemoteFilename());
        OPDE.info(
                SYSTools.xx("misc.msg.upload") + ": " + sysfile.getFilename() + " (" + sysfile.getMd5() + ")");
        //            fis.close();
    } else { // Ansonsten die bestehende Datei zurckgeben

        sysfile = alreadyExistingFiles.get(0);

        // Does the User own this file already ?
        //            for (SYSFiles mySYSfile : alreadyExistingFiles) {
        //                if (mySYSfile.getResident().equals(resident)) {
        //                    sysfile = mySYSfile;
        //                    break;
        //                }
        //            }
        //            if (sysfile == null) {
        //                sysfile = em.merge(new SYSFiles(file.getName(), md5, new Date(file.lastModified()), file.length(), OPDE.getLogin().getUser(), resident));
        //            }
    }

    return sysfile;
}

From source file:com.autentia.common.util.ejb.EntityManagerUtils.java

/**
 * Devuelve una lista de entidades de tipo <code>T</code>, obtenida como resultado de ejectua la consulta
 * <code>jpaql</code>, aadiendo un criterio de ordenacin, y haciendo la susticucin de parmetros (la sustitucin
 * de parmetros ser posicional)./*from  w ww.  j a va 2 s.  co  m*/
 * 
 * @param <T> tipo de los objetos devueltos por la bsqueda.
 * @param em el {@link EntityManager} donde se va a ejecutar la consulta.
 * @param jpaql consulta escrita en JPAQL.
 * @param sortAttribute nombre del atributo por el que se quiere ordenar.
 * @param ascending <code>true</code> si se quiere ordenar de forma ascendente. <code>false</code> para ordenacin
 *            descendente.
 * @param queryParams parmetros de la consulta. Son posicionales, de forma que la <code>jpaql</code> tendr ?1, ?2,
 *            ?3, ...
 * @return lista de entidades de tipo <code>T</code>, encontradas segn el criterio escrito en <code>jpaql</code>.
 */
public static <T> List<T> find(EntityManager em, String jpaql, String sortAttribute, boolean ascending,
        Object... queryParams) {

    String jpaqlWithOrderBy = jpaql;
    if (sortAttribute != null) {
        jpaqlWithOrderBy += " order by " + sortAttribute;
        if (ascending) {
            jpaqlWithOrderBy += " asc";
        } else {
            jpaqlWithOrderBy += " desc";
        }
    }

    if (log.isDebugEnabled()) {
        log.debug("Executing query: " + jpaqlWithOrderBy + ", with parameters: " + queryParams);
    }

    final Query query = em.createQuery(jpaqlWithOrderBy);
    return find(query, queryParams);
}

From source file:com.enioka.jqm.tools.ResourceParser.java

private static JndiResourceDescriptor fromDatabase(String alias) throws NamingException {
    JndiObjectResource resource = null;//  w w  w .  j  a  v  a  2  s.  c  o m
    EntityManager em = null;
    try {
        // Using the horrible CriteriaBuilder API instead of a string query. This avoids classloading issues - Hibernate binds
        // the entities at run time with the thread current classloader...
        em = Helpers.getNewEm();

        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<JndiObjectResource> q = cb.createQuery(JndiObjectResource.class);
        Root<JndiObjectResource> c = q.from(JndiObjectResource.class);
        ParameterExpression<String> p = cb.parameter(String.class);
        q.select(c).where(cb.equal(c.get("name"), p));

        TypedQuery<JndiObjectResource> query = em.createQuery(q);
        query.setParameter(p, alias);
        resource = query.getSingleResult();
    } catch (Exception e) {
        NamingException ex = new NamingException("Could not find a JNDI object resource of name " + alias);
        ex.setRootCause(e);
        throw ex;
    } finally {
        if (em != null) {
            em.close();
        }
    }

    // Create the ResourceDescriptor from the JPA object
    JndiResourceDescriptor d = new JndiResourceDescriptor(resource.getType(), resource.getDescription(), null,
            resource.getAuth(), resource.getFactory(), resource.getSingleton());
    for (JndiObjectResourceParameter prm : resource.getParameters()) {
        d.add(new StringRefAddr(prm.getKey(), prm.getValue()));
    }

    return d;
}

From source file:com.enioka.jqm.tools.Helpers.java

/**
 * Creates or updates metadata common to all nodes: default queue, global parameters, roles...<br>
 * It is idempotent. It also has the effect of making broken metadata viable again.
 *//* www . ja  v a 2 s  . c  o  m*/
static void updateConfiguration(EntityManager em) {
    em.getTransaction().begin();

    // Default queue
    Queue q = null;
    long i = (Long) em.createQuery("SELECT COUNT(qu) FROM Queue qu").getSingleResult();
    if (i == 0L) {
        q = new Queue();
        q.setDefaultQueue(true);
        q.setDescription("default queue");
        q.setTimeToLive(1024);
        q.setName("DEFAULT");
        em.persist(q);

        jqmlogger.info("A default queue was created in the configuration");
    } else {
        try {
            q = em.createQuery("SELECT q FROM Queue q WHERE q.defaultQueue = true", Queue.class)
                    .getSingleResult();
            jqmlogger.info("Default queue is named " + q.getName());
        } catch (NonUniqueResultException e) {
            // Faulty configuration, but why not
            q = em.createQuery("SELECT q FROM Queue q", Queue.class).getResultList().get(0);
            q.setDefaultQueue(true);
            jqmlogger.info("Queue " + q.getName()
                    + " was modified to become the default queue as there were mutliple default queue");
        } catch (NoResultException e) {
            // Faulty configuration, but why not
            q = em.createQuery("SELECT q FROM Queue q", Queue.class).getResultList().get(0);
            q.setDefaultQueue(true);
            jqmlogger.warn("Queue  " + q.getName()
                    + " was modified to become the default queue as there was no default queue");
        }
    }

    // Global parameters
    initSingleParam("mavenRepo", "http://repo1.maven.org/maven2/", em);
    initSingleParam(Constants.GP_DEFAULT_CONNECTION_KEY, Constants.GP_JQM_CONNECTION_ALIAS, em);
    initSingleParam("logFilePerLaunch", "true", em);
    initSingleParam("internalPollingPeriodMs", "60000", em);
    initSingleParam("disableWsApi", "false", em);
    initSingleParam("enableWsApiSsl", "false", em);
    initSingleParam("enableWsApiAuth", "true", em);
    initSingleParam("enableInternalPki", "true", em);

    // Roles
    RRole adminr = createRoleIfMissing(em, "administrator", "all permissions without exception", "*:*");
    createRoleIfMissing(em, "config admin",
            "can read and write all configuration, except security configuration", "node:*", "queue:*",
            "qmapping:*", "jndi:*", "prm:*", "jd:*");
    createRoleIfMissing(em, "config viewer", "can read all configuration except for security configuration",
            "node:read", "queue:read", "qmapping:read", "jndi:read", "prm:read", "jd:read");
    createRoleIfMissing(em, "client",
            "can use the full client API except reading logs, files and altering position", "node:read",
            "queue:read", "job_instance:*", "jd:read");
    createRoleIfMissing(em, "client power user", "can use the full client API", "node:read", "queue:read",
            "job_instance:*", "jd:read", "logs:read", "queue_position:create", "files:read");
    createRoleIfMissing(em, "client read only", "can query job instances and get their files", "queue:read",
            "job_instance:read", "logs:read", "files:read");

    // Users
    createUserIfMissing(em, "root", "all powerful user", adminr);

    // Mail session
    i = (Long) em.createQuery("SELECT COUNT(r) FROM JndiObjectResource r WHERE r.name = :nn")
            .setParameter("nn", "mail/default").getSingleResult();
    if (i == 0) {
        HashMap<String, String> prms = new HashMap<String, String>();
        prms.put("smtpServerHost", "smtp.gmail.com");

        JndiObjectResource res = new JndiObjectResource();
        res.setAuth(null);
        res.setDescription("default parameters used to send e-mails");
        res.setFactory("com.enioka.jqm.providers.MailSessionFactory");
        res.setName("mail/default");
        res.setType("javax.mail.Session");
        res.setSingleton(true);
        em.persist(res);

        JndiObjectResourceParameter prm = new JndiObjectResourceParameter();
        prm.setKey("smtpServerHost");
        prm.setValue("smtp.gmail.com");
        res.getParameters().add(prm);
        prm.setResource(res);
    }

    // Done
    em.getTransaction().commit();
}

From source file:com.enioka.jqm.tools.Main.java

private static void ws(String option) {
    if ("enable".equals(option)) {
        EntityManager em = Helpers.getNewEm();
        Helpers.setSingleParam("disableWsApi", "false", em);
        Helpers.setSingleParam("enableWsApiSsl", "false", em);
        Helpers.setSingleParam("enableWsApiAuth", "true", em);
        Helpers.setSingleParam("disableWsApiSimple", "false", em);
        Helpers.setSingleParam("disableWsApiClient", "false", em);
        Helpers.setSingleParam("disableWsApiAdmin", "false", em);
        Helpers.setSingleParam("enableInternalPki", "true", em);

        em.getTransaction().begin();/*from  w ww .j a v  a  2s  .c  om*/
        em.createQuery(
                "UPDATE Node n set n.loapApiSimple = true, n.loadApiClient = true, n.loadApiAdmin = true, n.dns=:n")
                .setParameter("n", "0.0.0.0").executeUpdate();
        em.getTransaction().commit();
        em.close();
    } else if ("disable".equals(option)) {
        EntityManager em = Helpers.getNewEm();
        em.getTransaction().begin();
        em.createQuery("UPDATE Node n set n.loadApiClient = false, n.loadApiAdmin = false").executeUpdate();
        em.getTransaction().commit();
        em.close();
    }
    if ("ssl".equals(option)) {
        EntityManager em = Helpers.getNewEm();
        Helpers.setSingleParam("enableWsApiSsl", "true", em);
        Helpers.setSingleParam("enableWsApiAuth", "true", em);
        em.close();
    }
    if ("nossl".equals(option)) {
        EntityManager em = Helpers.getNewEm();
        Helpers.setSingleParam("enableWsApiSsl", "false", em);
        em.close();
    }
    if ("internalpki".equals(option)) {
        EntityManager em = Helpers.getNewEm();
        Helpers.setSingleParam("enableInternalPki", "true", em);
        em.close();
    }
    if ("externalpki".equals(option)) {
        EntityManager em = Helpers.getNewEm();
        Helpers.setSingleParam("enableInternalPki", "false", em);
        em.close();
    }
}

From source file:com.siberhus.ngai.core.CrudHelper.java

@SuppressWarnings("unchecked")
public final static List<Object> findByExample(EntityManager em, Class<?> entityClass, Object example) {
    if (em == null) {
        throw new IllegalArgumentException("EntityManager is null");
    }/*  w  w  w  .  j  a va  2s  . c  o  m*/
    EntityInfo entityInfo = getEntityInfo(entityClass);
    List<Object> params = new ArrayList<Object>();
    StringBuilder sql = new StringBuilder(255);
    sql.append("from ").append(entityInfo.getEntityName()).append(" e where 1=1 ");
    try {
        for (Field field : entityInfo.getFieldSet()) {
            sql.append("and e.").append(field.getName()).append("=? ");
            params.add(field.get(example));
        }
    } catch (IllegalAccessException e) {
        throw new NgaiRuntimeException("Unable to get field value from example model: " + example, e);
    }
    Query query = em.createQuery(sql.toString());
    for (int i = 0; i < params.size(); i++) {
        query.setParameter(i + 1, params.get(i));
    }
    return query.getResultList();
}

From source file:net.anthonychaves.bookmarks.web.FakeLoginController.java

@RequestMapping(method = RequestMethod.POST)
public String fakeLogin(HttpSession session, @RequestParam("username") String username) {
    EntityManager em = emf.createEntityManager();
    Query q = em.createQuery("select u from User u where u.firstName = ?1").setParameter(1, username);

    User u = (User) q.getSingleResult();

    if (u != null) {
        session.setAttribute("user", u);
        return "redirect:user";
    } else {//from  w ww .j  a v  a2s. com
        return "redirect:/b/user/new";
    }
}

From source file:uk.co.threeonefour.ifictionary.web.user.dao.JpaUserDao.java

@Transactional
@Override/*from   www  . j a v  a 2s.  c om*/
public User findUser(String userId) {
    String query = "SELECT u FROM User AS u WHERE userId=:userId";
    EntityManager em = entityManager;
    Query q = em.createQuery(query.toString());
    q.setParameter("userId", userId);
    try {
        return (User) q.getSingleResult();
    } catch (NoResultException e) {
        return null;
    }
}