Example usage for javax.persistence EntityManager createNativeQuery

List of usage examples for javax.persistence EntityManager createNativeQuery

Introduction

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

Prototype

public Query createNativeQuery(String sqlString, String resultSetMapping);

Source Link

Document

Create an instance of Query for executing a native SQL query.

Usage

From source file:com.impetus.kvapps.runner.ExecutorService.java

/**
 * On find by native CQL3 query./*w  w  w . ja v  a 2 s .  co  m*/
 * 
 * @param em            entity manager instance.
 * @param query         native cql3 query.
 */
@SuppressWarnings("unchecked")
static void findByNativeQuery(final EntityManager em, final String query) {

    Query q = em.createNativeQuery(query, Tweets.class);

    Map<String, Client> clients = (Map<String, Client>) em.getDelegate();
    ThriftClient client = (ThriftClient) clients.get("twissandra");
    client.setCqlVersion(CassandraConstants.CQL_VERSION_3_0);

    logger.info("[On Find Tweets by CQL3]");
    List<Tweets> tweets = q.getResultList();

    System.out.println("#######################START##########################################");
    logger.info("\t\t User's total tweets:" + tweets.size());
    onPrintTweets(tweets);
    logger.info("\n");
    // logger.info("First tweet:" users.get(0).getTweets().);
    System.out.println("#######################END############################################");
    logger.info("\n");
}

From source file:org.ejbca.core.ejb.log.LogEntryData.java

/** @return a List<LogEntryData> from a custom SQL query. */
@SuppressWarnings("unchecked")
public static List<LogEntryData> findByCustomQueryAndPrivileges(EntityManager entityManager, String queryString,
        String caPriviledges, String viewLogPrivileges, int maxResults) {
    // Hibernate on DB2 wont allow us to "SELECT *" in combination with setMaxResults  
    String sql = "SELECT id, adminType, adminData, cAId, module, time, username, certificateSNR, event, logComment, rowVersion, rowProtection FROM LogEntryData WHERE ( "
            + queryString + ") AND (" + caPriviledges + ")";
    if (StringUtils.isNotEmpty(viewLogPrivileges)) {
        sql += " AND (" + viewLogPrivileges + ")";
    }/* ww w .  j a  v  a 2 s  .com*/
    sql += " ORDER BY time DESC";
    if (log.isDebugEnabled()) {
        log.debug("Query: " + sql);
    }
    Query query = entityManager.createNativeQuery(sql, LogEntryData.class);
    query.setMaxResults(maxResults);
    return query.getResultList();
}

From source file:de.berlios.jhelpdesk.dao.jpa.TicketCategoryDAOJpa.java

public List<TicketCategory> getAllCategories() {
    return (List<TicketCategory>) this.jpaTemplate.execute(new JpaCallback() {
        public Object doInJpa(EntityManager em) throws PersistenceException {
            Query q = em.createNativeQuery(
                    "SELECT * FROM ticket_category WHERE category_id>0 ORDER BY t_left ASC",
                    TicketCategory.class);
            return q.getResultList();
        }/*from w  ww  .j a va  2 s  .c  o  m*/
    });
}

From source file:de.berlios.jhelpdesk.dao.jpa.TicketCategoryDAOJpa.java

public List<TicketCategory> getAllCategoriesForView() {
    return (List<TicketCategory>) this.jpaTemplate.execute(new JpaCallback() {
        public Object doInJpa(EntityManager em) throws PersistenceException {
            Query q = em.createNativeQuery(
                    "SELECT * FROM ticket_category "
                            + "WHERE is_active IS true AND category_id > 0 ORDER BY t_left ASC",
                    TicketCategory.class);
            return q.getResultList();
        }/*  w  ww  . j  a  v a 2s  .c o m*/
    });
}

From source file:com.opensymphony.able.service.JpaCrudService.java

/**
 * Performs a native SQL query with optional parameters using a named SQL result set mapping
 *///from  w  ww . j a  v  a  2 s  .  com
protected List findUsingSqlResultSetMapping(final String sql, final String resultSetMapping,
        final Object... parameters) {
    return getJpaTemplate().executeFind(new JpaCallback() {
        public Object doInJpa(EntityManager entityManager) throws PersistenceException {
            Query query = entityManager.createNativeQuery(sql, resultSetMapping);
            int index = 1;
            for (Object parameter : parameters) {
                System.out.println("Setting param: " + index + " to: " + parameter);
                query.setParameter(index++, parameter);
            }
            return query.getResultList();
        }
    });
}

From source file:de.berlios.jhelpdesk.dao.jpa.TicketCategoryDAOJpa.java

@Transactional(readOnly = false)
public void insertRootCategory(final TicketCategory rootCategory) {
    this.jpaTemplate.execute(new JpaCallback() {
        public Object doInJpa(EntityManager em) throws PersistenceException {
            Query getMaxTRightQuery = em.createNativeQuery("SELECT max(t_right) FROM ticket_category",
                    Long.class);
            final Long maxTRight = (Long) getMaxTRightQuery.getSingleResult();

            rootCategory.setLeft(new Long(maxTRight.longValue() + 1));
            rootCategory.setRight(new Long(maxTRight.longValue() + 2));
            rootCategory.setDepth(0);// w  ww . ja  v a2s. c o  m
            em.persist(rootCategory);
            return null;
        }
    });
}

From source file:com.opensymphony.able.service.JpaCrudService.java

/**
 * Quries entities of the given type using native SQL and optional parameters
 *///from ww  w . jav  a  2 s  .c o m
protected List findTypeUsingSql(final String sql, final Class returnType, final Object... parameters) {
    return getJpaTemplate().executeFind(new JpaCallback() {
        public Object doInJpa(EntityManager entityManager) throws PersistenceException {
            System.out.println("About to perform sql: " + sql + " to return type: " + returnType);
            Query query = entityManager.createNativeQuery(sql, returnType);
            int index = 1;
            for (Object parameter : parameters) {
                System.out.println("Setting param: " + index + " to: " + parameter);
                query.setParameter(index++, parameter);
            }
            return query.getResultList();
        }
    });
}

From source file:us.co.douglas.assessor.dao.AccountDAOImpl.java

public OwnerAddress getOwnerAddress(String accountNo) {
    log.info("getOwnerAddress()...");
    EntityManager entityManager = getEntityManager();
    try {//  w  w w  .  j  a  v  a2s.  c  o m
        Query query = entityManager.createNativeQuery("SELECT DISTINCT " + "TBLACCT.ACCOUNTNO, "
                + "(ISNULL(TBLADDRESSSECURE.ADDRESS1, '') + ISNULL(TBLADDRESSSECURE.ADDRESS2, '')) AS streetAddress, "
                + "ISNULL(TBLADDRESSSECURE.CITY, '')  AS cityName, "
                + "ISNULL(TBLADDRESSSECURE.STATECODE, '')  AS stateName, "
                + "ISNULL(SUBSTRING(TBLADDRESSSECURE.ZIPCODE, 1, 5), '')  AS ZIPCODE " + "FROM "
                + "ENCOMPASS.TBLACCT TBLACCT "
                + "join encompass.TBLACCTOWNERADDRESS TBLACCTOWNERADDRESS on TBLACCTOWNERADDRESS.ACCOUNTNO = TBLACCT.ACCOUNTNO "
                + "join encompass.TBLADDRESSSECURE TBLADDRESSSECURE on TBLADDRESSSECURE.ADDRESSCODE = TBLACCTOWNERADDRESS.ADDRESSCODE "
                + "WHERE TBLACCT.VEREND = 99999999999 " + "AND TBLACCTOWNERADDRESS.VEREND = 99999999999 "
                + "AND TBLADDRESSSECURE.VEREND = 99999999999" + "AND TBLACCT.ACCOUNTNO = :accountNo ",
                OwnerAddress.class);
        query.setMaxResults(maxResults);
        query.setParameter("accountNo", accountNo);
        List<OwnerAddress> addressList = query.getResultList();
        if (addressList.size() > 0) {
            return addressList.get(0);
        } else {
            return null;
        }
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    } finally {
        entityManager.close();
    }
}

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

@SuppressWarnings("unchecked")
@Override/*w  w  w .  j a va 2s  .  c o m*/
public <T> List<T> findByQueryAndMapDefault(Class<T> resultClass, String nativeQuery, List<Object> posParams) {
    EntityManager em = JpaUtil.createEntityManager(this.getEntityManagerFactory());
    try {
        Query query = em.createNativeQuery(nativeQuery, resultClass);
        JpaUtil.bindQueryParams(query, posParams);
        return query.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.  jav a2 s .c o  m*/
 */
@SuppressWarnings("unchecked")
@Override
public <T> List<T> findByQueryAndMapResultSet(Class<T> resultClass, ResultSetMappingDTO mappingDTO) {
    EntityManager em = JpaUtil.createEntityManager(this.getEntityManagerFactory());
    try {
        Query query = em.createNativeQuery(mappingDTO.getNativeQuery(), mappingDTO.getResultSetMapping());
        JpaUtil.bindQueryParams(query, mappingDTO.getPosParams());
        return query.getResultList();
    } catch (Exception ex) { // NOSONAR
        throw new JpaException(ex);
    } finally {
        JpaUtil.closeEntityManager(em);
    }
}