Example usage for org.hibernate SQLQuery addEntity

List of usage examples for org.hibernate SQLQuery addEntity

Introduction

In this page you can find the example usage for org.hibernate SQLQuery addEntity.

Prototype

SQLQuery<T> addEntity(Class entityType);

Source Link

Document

Declare a "root" entity, without specifying an alias.

Usage

From source file:com.waveerp.TableWtmTimeDataRaw.java

License:Open Source License

public String changeDataStatus(String pJuid, String pField, String pData) {

    List<Wtmtimedataraw> myList = null;
    Iterator<Wtmtimedataraw> iterator = null;
    Wtmtimedataraw item = null;//from   w w w.j  av  a2s  .c o m

    String strResult = "ERROR";

    try {
        dbServices.begin();

        Session session = dbServices.getDataServiceManager().getSession();
        String sQuery = "select * from Wtmtimedataraw where juid = '" + pJuid + "' ;";

        SQLQuery query = session.createSQLQuery(sQuery);
        query.addEntity(Wtmtimedataraw.class);

        myList = query.list();

        dbServices.commit();

        iterator = myList.iterator();

        /**
         * At this point, only one record should be retrieved
        */
        while (iterator.hasNext()) {

            item = (Wtmtimedataraw) iterator.next();

        }

    } catch (Exception e) {

        dbServices.rollback();
        return "FAIL";

    }

    // Update the object
    if (item == null) {
        //Do nothing
        strResult = "FAIL";
    } else {

        if (pField.compareTo("DATASTAT") == 0) {

            item.setDatastat(pData);

        } else if (pField.compareTo("DATASRC") == 0) {

            item.setDatasrc(pData);

        } else if (pField.compareTo("AXING") == 0) {

            item.setAxing(pData);

        } else if (pField.compareTo("USEINOUT") == 0) {

            item.setUseinout(pData);

        } else {

            strResult = "FAIL";

        }

        //Do the update now.  
        try {

            dbServices.begin();
            dbServices.update(item);
            dbServices.commit();

            strResult = "OK";

        } catch (Exception e) {

            strResult = "FAIL";
            return e.getMessage();

        }

    }

    return strResult;

}

From source file:Configuration.UserHelper.java

public boolean loginUser(String username, String password)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
    try {//from   w  w w.  j a va  2  s. c o  m
        tx = session.beginTransaction();
        SQLQuery q = session.createSQLQuery(
                "Select UserName, UserPassword from Users where UserName =? and UserPassword =?");
        q.addEntity(Users.class);
        q.setParameter(0, username);
        q.setParameter(1, password);
        List result = q.list();
        Users tmpuser = (Users) result.get(0);

        System.out.println("tmpuser" + tmpuser);

        //System.out.println(tmpuser.getFirstName());

        //System.out.println("yyyyyyyy " + result.get(0));

        //q.setParameter(1, byteArrayToHexString(getEncryptedPassword(password, salt)));
        //            byte[] saltByte=hexStringtoByteArry();
        //            Users user = (Users) q.
        //            String pass = user.getUserPassword();
        // session.close();
    } catch (HibernateException e) {
        e.printStackTrace();
        try {
            tx.rollback();
        } catch (RuntimeException r) {
            System.out.println("Can't rollback transaction");

        }
        throw e;
    } finally {
        if (session != null) {
            session.close();
        }
    }
    return false;
}

From source file:Consultas.FrmBuscarProducto.java

private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuscarActionPerformed
    // TODO add your handling code here:

    String textoBusqueda = this.txtNombreID.getText();

    Session session = HibernateUtil.getInstance().getSession();
    session.beginTransaction();//  w  w w . ja  v  a 2  s  .  c o  m

    SQLQuery query = session
            .createSQLQuery("SELECT * FROM producto WHERE codigo = :codigo OR nombre LIKE :nombre");
    query.addEntity(ClsEntidadProductoHib.class);
    query.setString("codigo", textoBusqueda);
    query.setString("nombre", "%" + textoBusqueda + "%");
    this.resultados = query.list();

    DefaultTableModel dtm = new DefaultTableModel();
    String titulos[] = { "ID", "Codigo", "Nombre", "Descripcion", "Precio Venta" };
    dtm.setColumnIdentifiers(titulos);

    for (ClsEntidadProductoHib producto : this.resultados) {
        String datos[] = { producto.getIdProducto().toString(), producto.getCodigo(), producto.getNombre(),
                producto.getDescripcion(), producto.getPrecioVenta().toString() };
        dtm.addRow(datos);
    }

    this.tblResultados.setModel(dtm);
    this.tblResultados.changeSelection(0, 0, false, false);

    session.close();
}

From source file:dao.AdDao.java

public List<Ad> getAdsByUser(Long userId) {
    String sql = "select * from ad where author_id=:userId and date_to>:now and :now>date_from";
    SQLQuery query = getCurrentSession().createSQLQuery(sql);
    query.setParameter("userId", userId);
    query.setParameter("now", new Date());
    query.addEntity(Ad.class);
    return query.list();
}

From source file:dao.AdDao.java

public List<Ad> getChosenAds(Long userId) {
    String sql = "select a.* from chosen_ads ca left join ad a on ca.ad_id=a.ad_id where ca.user_id=:userId and a.date_to>:now and :now>a.date_from";
    SQLQuery query = getCurrentSession().createSQLQuery(sql);
    query.setParameter("userId", userId);
    query.setParameter("now", new Date());
    query.addEntity(Ad.class);
    return query.list();
}

From source file:dao.AdDao.java

public List<Ad> getSales(Long userId) {
    String sql = "select * from ad where author_id=:userId";
    SQLQuery query = getCurrentSession().createSQLQuery(sql);
    query.setParameter("userId", userId);
    query.addEntity(Ad.class);
    return query.list();
}

From source file:dao.AdDao.java

public List<Ad> getPurchases(Long userId) {
    String sql = "select * from ad where buyer_id=:userId order by sale_date";
    SQLQuery query = getCurrentSession().createSQLQuery(sql);
    query.setParameter("userId", userId);
    query.addEntity(Ad.class);
    return query.list();
}

From source file:dao.AdDao.java

public List<Ad> getAdsByWishInNameOrDescription(String wish, List<Long> catIds, Region region, String order,
        List<Long> booleanIds, List<Long> booleanVals, List<Long> stringIds, List<String> stringVals,
        List<BilateralCondition> numVals, List<BilateralCondition> dateVals, List<Long> selIds,
        List<Long> selVals, String multyVals[], Double priceFrom, Double priceTo) throws Exception {
    if (order == null) {
        order = "show_count desc";
    }// ww  w  .  ja  v  a  2 s.c  om
    String sql = "select * from ad where date_from<:now and :now<date_to";
    if (wish == null) {
        wish = "";
    }
    List<String> splitted = splitted(wish);
    if (!splitted.isEmpty()) {
        sql += " and (1!=1";
        for (String st : splitted) {
            sql += " or (name like :wish" + splitted.indexOf(st) + ")";
        }
        for (String st : splitted) {
            sql += " or (description like :wish" + splitted.indexOf(st) + ")";
        }
        sql += ")";
    }

    if (!catIds.isEmpty()) {
        sql += " and (1!=1";
        for (Long id : catIds) {
            sql += " or category_id=:catId" + catIds.indexOf(id);
        }
        sql += ")";
    }

    if (region != null && !region.isAllRussia()) {
        sql += " and ad_id in (select ad_id from ads_at_locals where locality_id in (:localIds))";
    }

    /**
     * ?? ? *
     */

    if (priceFrom != null) {
        sql += " and price>=:priceFrom";
    }
    if (priceTo != null) {
        sql += " and price<=:priceTo";
    }
    Integer paramsCount = 0;
    Boolean queryWithParams = false;
    if ((stringVals != null && !stringVals.isEmpty()) || (booleanVals != null && !booleanVals.isEmpty())
            || (numVals != null && !numVals.isEmpty()) || (dateVals != null && !dateVals.isEmpty())
            || (selVals != null && !selVals.isEmpty()) || (multyVals != null && multyVals.length > 0)) {

        queryWithParams = true;
        sql += " and exists(select 1 from (select count(pv.ad_id) cnt,pv.ad_id id from parametr_value pv where (1!=1)";
        int i = 0;

        if (stringVals != null && !stringVals.isEmpty()) {
            i = 0;
            for (String val : stringVals) {
                sql += " or (parametr_id=:stringId" + i + " and string_value like '%:stringVal" + i + "%')";
                paramsCount++;
                i++;
            }

        }

        if (numVals != null && !numVals.isEmpty()) {
            i = 0;
            for (BilateralCondition c : numVals) {
                Double numFrom = (Double) c.getFrom();
                Double numTo = (Double) c.getTo();
                if (numFrom != null || numTo != null) {

                    if (numFrom != null && numTo != null) {
                        sql += " or (parametr_id=:numId" + i + " and number_value >= :numFrom" + i
                                + " and number_value <= :numTo" + i + ")";
                    } else {
                        if (numFrom != null) {
                            sql += " or (parametr_id=:numId" + i + " and number_value >= :numFrom" + i + ")";
                        }
                        if (numTo != null) {
                            sql += " or (parametr_id=:numId" + i + " and number_value <= :numTo" + i + ")";
                        }
                    }
                    paramsCount++;
                    i++;
                }
            }

        }

        if (dateVals != null && !dateVals.isEmpty()) {
            i = 0;
            for (BilateralCondition c : dateVals) {
                Date dateFrom = (Date) c.getFrom();
                Date dateTo = (Date) c.getTo();
                if (dateFrom != null || dateTo != null) {
                    if (dateFrom != null && dateTo != null) {
                        sql += " or (parametr_id=:dateId" + i + " and date_value >= :dateFrom" + i
                                + " and date_value <= :dateTo" + i + ")";
                    } else {
                        if (dateFrom != null) {
                            sql += " or (parametr_id=:dateId" + i + " and date_value >= :dateFrom" + i + ")";
                        }
                        if (dateTo != null) {
                            sql += " or (parametr_id=:dateId" + i + " and date_value <= :dateTo" + i + ")";
                        }
                    }
                    paramsCount++;
                    i++;
                }
            }
        }

        /*if (booleanVals != null && booleanVals.length > 0) {
        i = 0;
        while (i < booleanIds.length) {
            Long paramId = booleanIds[i];
            Long val = booleanVals[i];
            if (val != null) {
                sql += " or (parametr_id=" + paramId + " and select_value=" + val + ")";
                paramsCount++;
            }
            i++;
        }
        }
                
        if (selVals != null && selVals.length > 0) {
        i = 0;
        while (i < selIds.length) {
            Long paramId = selIds[i];
            Long val = selVals[i];
            if (val != null) {
                sql += " or (parametr_id=" + paramId + " and select_value=" + val + ")";
                paramsCount++;
            }
            i++;
        }
        }*/

        if (booleanVals != null && !booleanVals.isEmpty()) {
            i = 0;
            for (Long val : booleanVals) {
                if (val != null) {
                    sql += " or (parametr_id=:booleanId" + i + " and select_value=:booleanVal" + i + ")";
                    paramsCount++;
                    //ex+=i+":"+val+"; ";
                }
                i++;
            }
        }

        if (selVals != null && !selVals.isEmpty()) {
            i = 0;
            for (Long val : selVals) {
                if (val != null) {
                    sql += " or (parametr_id=:selId" + i + " and select_value=:selVal" + i + ")";
                    paramsCount++;
                    //ex+=i+":"+val+"; ";
                }
                i++;
            }
        }

        if (multyVals != null && multyVals.length > 0) {

            for (String rawVal : multyVals) {
                String idValArr[] = rawVal.split("_");
                if (idValArr.length == 2) {
                    String strId = idValArr[0];
                    String strVal = idValArr[1];
                    Long paramId = Long.valueOf(strId);
                    Long val = Long.valueOf(strVal);
                    if (val != null) {
                        sql += " or (parametr_id=" + paramId + " and select_value=" + val + ")";
                        paramsCount++;
                    }
                }
            }

        }

        sql += " group by pv.ad_id) as tmp where tmp.cnt=:paramsCount and tmp.id=ad.ad_id)";
    }
    /**
     * \?? ? *
     */
    sql += " order by status asc," + order;

    SQLQuery query = getCurrentSession().createSQLQuery(sql);

    if (!splitted.isEmpty()) {
        for (String st : splitted) {
            query.setParameter("wish" + splitted.indexOf(st), st);
        }
    }
    if (!catIds.isEmpty()) {
        for (Long id : catIds) {
            query.setParameter("catId" + catIds.indexOf(id), id);
        }
    }
    if (priceFrom != null) {
        query.setParameter("priceFrom", priceFrom);
    }
    if (priceTo != null) {
        query.setParameter("priceTo", priceTo);
    }
    if (stringVals != null && !stringVals.isEmpty()) {
        int i = 0;
        for (String s : stringVals) {
            query.setParameter("stringId" + i, stringIds.get(i));
            query.setParameter("stringVal" + i, stringVals.get(i));
            i++;
        }
    }
    if (booleanVals != null && !booleanVals.isEmpty()) {
        int i = 0;
        for (Long v : booleanVals) {
            if (v != null) {
                query.setParameter("booleanId" + i, booleanIds.get(i));
                query.setParameter("booleanVal" + i, v);
            }
            i++;
        }

    }
    if (selVals != null && !selVals.isEmpty()) {
        int i = 0;
        for (Long v : selVals) {
            if (v != null) {
                query.setParameter("selId" + i, selIds.get(i));
                query.setParameter("selVal" + i, v);
            }
            i++;
        }

    }
    if (numVals != null && !numVals.isEmpty()) {
        int i = 0;
        for (BilateralCondition c : numVals) {
            Long id = c.getId();
            Double numFrom = (Double) c.getFrom();
            Double numTo = (Double) c.getTo();
            query.setParameter("numId" + i, id);
            if (numFrom != null) {
                query.setParameter("numFrom" + i, numFrom);
            }
            if (numTo != null) {
                query.setParameter("numTo" + i, numTo);
            }
            i++;
        }
    }
    if (dateVals != null && !dateVals.isEmpty()) {
        int i = 0;
        for (BilateralCondition c : dateVals) {
            Long id = c.getId();
            Date dateFrom = (Date) c.getFrom();
            Date dateTo = (Date) c.getTo();
            query.setParameter("dateId" + i, id);
            if (dateFrom != null) {
                query.setParameter("dateFrom" + i, dateFrom);
            }
            if (dateTo != null) {
                query.setParameter("dateTo" + i, dateTo);
            }
            i++;
        }
    }
    if (queryWithParams) {
        query.setParameter("paramsCount", paramsCount);
    }
    query.setParameter("now", new Date());
    if (region != null && !region.isAllRussia()) {
        query.setParameterList("localIds", getLocIds(region));
    }
    query.addEntity(Ad.class);
    if (1 == 1) {
        //throw new Exception("e="+ex+"; bv:"+booleanVals.size()+"; sv:"+selVals.size()+"; pc:"+paramsCount);
    }
    //throw new Exception(sql);

    return query.list();
}

From source file:DAO.AsistenciaDAO.java

public List<Asistencia> getAllAsistanceByAsignature(String DOC_COD, int INS_DCODIGO, int MUN_ID, int DEP_ID,
        int SEC_CODIGO, int ASI_COD, int CUR_COD) {
    SessionFactory sf = HibernateUtil.getSessionFactory();
    Session session = sf.openSession();/*from w  ww . j a  va  2s  .  c om*/
    SQLQuery sQLQuery = session
            .createSQLQuery(sqlGenerator(DOC_COD, INS_DCODIGO, MUN_ID, DEP_ID, SEC_CODIGO, ASI_COD, CUR_COD));
    sQLQuery.addEntity(Asistencia.class);
    List<Asistencia> listA = sQLQuery.list();
    return listA;
}

From source file:DAO.AsistenciaDAO.java

public List<Asistencia> getAllAsistanceByAsignature(String DOC_COD, int ASI_COD) {
    SessionFactory sf = HibernateUtil.getSessionFactory();
    Session session = sf.openSession();/*from ww  w  .jav a2  s  . co  m*/
    SQLQuery sQLQuery = session.createSQLQuery(sqlGenerator(DOC_COD, ASI_COD));
    sQLQuery.addEntity(Asistencia.class);
    List<Asistencia> listA = sQLQuery.list();
    return listA;
}