Example usage for org.hibernate Session createSQLQuery

List of usage examples for org.hibernate Session createSQLQuery

Introduction

In this page you can find the example usage for org.hibernate Session createSQLQuery.

Prototype

@Override
    NativeQuery createSQLQuery(String queryString);

Source Link

Usage

From source file:com.amalto.core.storage.hibernate.HibernateStorage.java

License:Open Source License

@SuppressWarnings("rawtypes")
private void deleteData(ComplexTypeMetadata typeToDelete, Map<String, List> condition, TypeMapping mapping) {
    Session session = this.getCurrentSession();
    for (FieldMetadata field : typeToDelete.getFields()) {
        if (field.isMany()) {
            String formattedTableName = tableResolver.getCollectionTable(field);
            String deleteFormattedTableSQL = "delete from " + formattedTableName; //$NON-NLS-1$
            if (!condition.isEmpty()) {
                deleteFormattedTableSQL = deleteFormattedTableSQL + " where " + conditionMapToString(condition); //$NON-NLS-1$                    
            }//from  www .  j a v a  2s .c o  m
            session.createSQLQuery(deleteFormattedTableSQL).executeUpdate();
        }
    }
    // Delete the type instances
    String className = storageClassLoader.getClassFromType(typeToDelete).getName();
    String hql = "delete from " + className; //$NON-NLS-1$
    org.hibernate.Query query = session.createQuery(hql);
    if (!condition.isEmpty()) {
        hql = hql + " where "; //$NON-NLS-1$
        for (Entry<String, List> fieldEntry : condition.entrySet()) {
            if (!hql.endsWith("where ")) { //$NON-NLS-1$
                hql = hql + " and "; //$NON-NLS-1$
            }
            hql = hql + fieldEntry.getKey() + " in (:" + fieldEntry.getKey() + ")"; //$NON-NLS-1$//$NON-NLS-2$
        }
        query = session.createQuery(hql);
        for (Entry<String, List> fieldEntry : condition.entrySet()) {
            query.setParameterList(fieldEntry.getKey(), fieldEntry.getValue());
        }
    }
    query.executeUpdate();
    // Clean up full text indexes
    if (dataSource.supportFullText()) {
        FullTextSession fullTextSession = Search.getFullTextSession(session);
        Set<Class<?>> indexedTypes = fullTextSession.getSearchFactory().getIndexedTypes();
        Class<? extends Wrapper> entityType = storageClassLoader.getClassFromType(mapping.getDatabase());
        if (indexedTypes.contains(entityType)) {
            fullTextSession.purgeAll(entityType);
        } else {
            LOGGER.warn("Unable to delete full text indexes for '" + entityType + "' (not indexed)."); //$NON-NLS-1$ //$NON-NLS-2$
        }
    }
}

From source file:com.anhtran.productimage.dao.impl.ProductDaoImpl.java

License:Open Source License

@SuppressWarnings("unchecked")
public List<Product> getAllProductExcludingRelationship() {
    Session session = sessionFactory.getCurrentSession();
    Query query = session.createSQLQuery("select * from product").addEntity(Product.class);
    List<Product> result = query.list();
    return result;
}

From source file:com.anhtran.productimage.dao.impl.ProductDaoImpl.java

License:Open Source License

@SuppressWarnings("unchecked")
public Product getProductExcludingRelationshipFromId(int productId) {
    Session session = sessionFactory.getCurrentSession();
    Query query = session.createSQLQuery("select * from product p where p.id = :productId")
            .addEntity(Product.class).setParameter("productId", productId);
    List<Product> result = query.list();
    return result.size() > 0 ? result.get(0) : null;
}

From source file:com.asecurity.eventslogdb.AccessEvents.java

private List<ApacseventsCha> getApacseventsCha(String hql, int resCnt, boolean useNativeSQL) {
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    List<ApacseventsCha> aeCha = null;
    Transaction tx = null;//from  www.j  ava2  s  .  c o  m
    try {
        tx = session.beginTransaction();
        Query q;
        if (useNativeSQL) {
            q = session.createSQLQuery(hql);
            q.setResultTransformer(Transformers.aliasToBean(ApacseventsCha.class));
        } else {
            q = session.createQuery(hql);
        }
        q.setMaxResults(resCnt);
        aeCha = (List<ApacseventsCha>) q.list();
    } catch (Exception e) {
        System.out.println(e.toString());
    } finally {
        if (tx != null) {
            tx.rollback();
        }
        if (session.isOpen()) {
            session.close();
        }
    }
    return aeCha;
}

From source file:com.asociate.dao.EventoAsistentesDAO.java

/**
 *
 * @param idEvento/*from w  w  w  . j  a v a 2s . c om*/
 * @return
 */
public List<Persona> getListaEvento(Long idEvento) {
    Session sesion = HibernateUtil.getSessionFactory().openSession();
    List<Persona> salida = new ArrayList();
    try {
        Query qu = sesion.createSQLQuery(
                "Select P.* from PERSONA P join EVENTO_ASISTENTES E on E.ID_PERSONA = P.ID_PERSONA WHERE E.ID_EVENTO = :idE AND E.ESTADO = 'A' ");
        qu.setParameter("idE", idEvento);
        salida = qu.list();

    } catch (JDBCException c) {
        c.printStackTrace();

    } catch (Exception e) {
        e.printStackTrace();

    } finally {
        sesion.flush();
        sesion.close();
    }

    return salida;
}

From source file:com.asociate.dao.UsuarioDAO.java

/**
 *
 * @param query//  ww  w.  j  a va 2s . c  o  m
 * @param idUsuario
 * @return
 */
public List<Usuario> buscarContacto(String query, Long idUsuario) {
    Session sesion = HibernateUtil.getSessionFactory().openSession();
    List<Usuario> salida = new ArrayList<>();
    try {
        Query qu = sesion.createSQLQuery("Select U.* from usuario U "
                + "join amistad A on A.id_amigo=U.id_usuario" + " where A.id_origen = :idUsuario  and "
                + "A.id_amigo in(" + "(Select P.id_usuario from persona P where lower(nombre) like lower('%"
                + query + "%') " + " or lower(apellidop) like lower('%" + query + "%')) union "
                + "(Select S.id_usuario from asociacion S where lower(razonsocial) like lower('%" + query
                + "%') )" + ")");
        qu.setParameter("idUsuario", idUsuario);
        salida = qu.list();

    } catch (RuntimeException e) {
        e.printStackTrace();
    } finally {
        sesion.flush();
        sesion.close();
    }
    return salida;
}

From source file:com.assignment.elance.modelManager.JobManager.java

public int insert(int category_id, ArrayList<Integer> skill, String title, String description, float cost,
        Employer emp) {//ww w .ja v a 2 s  .  com
    int lastId;
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    session.beginTransaction();

    Query query = session.createSQLQuery(
            "INSERT INTO `job`(`job_title`, `job_description`, `job_cost`, `time_period`, `job_posted_date`, `job_status`, `employer_id`,  `category_id`) VALUES (:job_title, :job_description, :job_cost, :time_period, :job_posted_date, :job_status, :employer_id, :category_id)")
            .setParameter("job_title", title).setParameter("job_description", description)
            .setParameter("job_cost", cost).setParameter("time_period", new Long(00))
            .setParameter("job_posted_date", new Date())
            .setParameter("job_status", SystemAttributes.JobStatuses.OPEN)
            .setParameter("employer_id", emp.getEmployer_id())
            //                .setParameter("bidder_id", null)
            .setParameter("category_id", category_id);
    query.executeUpdate();
    lastId = ((BigInteger) session.createSQLQuery("SELECT LAST_INSERT_ID()").uniqueResult()).intValue();

    session.getTransaction().commit();
    insertJobSkills(lastId, skill);
    return lastId;
}

From source file:com.assignment.elance.modelManager.JobManager.java

private void insertJobSkills(int job_id, ArrayList<Integer> skill) {

    Session session2 = HibernateUtil.getSessionFactory().getCurrentSession();
    session2.beginTransaction();//from  w  w w.ja v a  2s. com
    for (int skill_id : skill) {

        Query query2 = session2.createSQLQuery(
                "INSERT INTO `job_skill`(`job_id`, `skill_id`,`bidder_id`) VALUES (:job_id,:skill_id,:bidder_id)")
                .setParameter("job_id", job_id).setParameter("skill_id", skill_id).setParameter("bidder_id", 1);
        query2.executeUpdate();
    }
    session2.getTransaction().commit();
}

From source file:com.atsamour.habitatweave.controller.ActivityServlet.java

License:Open Source License

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request/*from  w ww .  j  ava  2s. co  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    request.setAttribute("hide", "hide");

    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    session.beginTransaction();
    //Retrives the min and max date with available data form the measurement table
    Query query = session.createSQLQuery(
            "SELECT `start_time` FROM measurement WHERE type = 'Calories' ORDER BY start_time ASC LIMIT 1");
    List<Object> result = query.list();
    Date date = new Date();
    date = (java.sql.Timestamp) (result.get(0));
    //Attributes used at datetimepicker JavaScript
    request.getSession().setAttribute("minD", date);
    query = session.createSQLQuery(
            "SELECT `start_time` FROM measurement WHERE type = 'Calories' ORDER BY start_time DESC LIMIT 1");
    result = query.list();
    date = (java.sql.Timestamp) (result.get(0));
    request.getSession().setAttribute("maxD", date);

    if (session.isOpen()) {
        session.close();
    }
    RequestDispatcher rd = getServletContext().getRequestDispatcher("/secure/activity.jsp");
    rd.forward(request, response);
}

From source file:com.atsamour.habitatweave.controller.ActivityServlet.java

License:Open Source License

public List<Object[]> getActivityMeasurement(Session session, String person_id, Date date1, Date date2) {
    Query query = session
            .createSQLQuery("SELECT `date`, SUM(measurement.value) AS value, HOUR(measurement.start_time)"
                    + " as start_time, `type` FROM measurement WHERE "
                    + "measurement.person_id=:pid AND type IN ( 'Calories', 'MovingIntensity' )"
                    + " AND date BETWEEN :date1 AND :date2 GROUP BY date, HOUR(start_time), type")
            .setString("pid", person_id).setDate("date1", date1).setDate("date2", date2);
    List<Object[]> result = query.list();
    return result;
}