Example usage for org.hibernate Query setDouble

List of usage examples for org.hibernate Query setDouble

Introduction

In this page you can find the example usage for org.hibernate Query setDouble.

Prototype

@Deprecated
@SuppressWarnings("unchecked")
default Query<R> setDouble(String name, double val) 

Source Link

Document

Bind a named double-valued parameter.

Usage

From source file:com.exilant.eGov.src.domain.GeneralLedger.java

License:Open Source License

@SuppressWarnings("deprecation")
@Transactional/* w w w  .ja va  2 s. co  m*/
public void insert() throws SQLException, TaskFailedException {
    final EGovernCommon commommethods = new EGovernCommon();
    Query pst = null;
    try {
        effectiveDate = String.valueOf(commommethods.getCurrentDate());
        Date dt = new Date();
        final SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        final SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
        dt = sdf.parse(effectiveDate);
        effectiveDate = formatter.format(dt);

        description = commommethods.formatString(description);
        setId(String.valueOf(PrimaryKeyGenerator.getNextKey("GeneralLedger")));

        if (functionId == null || functionId.equals(""))
            functionId = null;
        String insertQuery;
        insertQuery = "INSERT INTO generalledger (id, voucherLineID, effectiveDate, glCodeID, "
                + "glCode, debitAmount, creditAmount,";
        insertQuery += "description,voucherHeaderId,functionId) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

        if (LOGGER.isInfoEnabled())
            LOGGER.info(insertQuery);
        pst = persistenceService.getSession().createSQLQuery(insertQuery);
        pst.setBigInteger(0, BigInteger.valueOf(Long.valueOf(id)));
        pst.setBigInteger(1,
                voucherLineId == null ? BigInteger.ZERO : BigInteger.valueOf(Long.valueOf(voucherLineId)));
        pst.setTimestamp(2, dt);
        pst.setBigInteger(3,
                glCodeId.equalsIgnoreCase("null") ? null : BigInteger.valueOf(Long.valueOf(glCodeId)));
        pst.setString(4, glCode);
        pst.setDouble(5, debitAmount.equalsIgnoreCase("null") ? null : Double.parseDouble(debitAmount));
        pst.setDouble(6, creditAmount.equalsIgnoreCase("null") ? null : Double.parseDouble(creditAmount));
        pst.setString(7, description);
        pst.setBigInteger(8, voucherHeaderId.equalsIgnoreCase("null") ? null
                : BigInteger.valueOf(Long.valueOf(voucherHeaderId)));
        pst.setBigInteger(9, functionId == null ? null : BigInteger.valueOf(Long.valueOf(functionId)));
        pst.executeUpdate();
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        throw taskExc;
    } finally {
    }

}

From source file:com.less.hibernatebasicmaven.Main.java

private static void testSQL() {
    Session session = null;/*ww  w  . ja va  2s  .  co  m*/
    try {
        session = HibernateUtil.getSessionFactory().openSession();

        // Simple SQL example
        p("\nSimple SQL query");

        Query query1 = session.createSQLQuery("SELECT * FROM users WHERE id between 10 AND 15; ")
                .addEntity(User.class);
        List<User> users1 = query1.list();
        p("Simple select:");
        printUsers(new ArrayList<User>(users1));

        // Prepared SQL Example
        p("\nPrepared by name example");

        Query query2 = session
                .createSQLQuery(
                        "SELECT * FROM users WHERE name IN (:name1, :name2) AND gender = :gen LIMIT 0, 3;")
                .addEntity(User.class);
        query2.setString("name1", "Vasya Pupkin");
        query2.setString("name2", "Tony Stark");
        query2.setString("gen", User.Gender.MALE);
        List<User> users2 = query2.list();
        p("Select with named params:");
        printUsers(new ArrayList<User>(users2));

        // Prepared by index SQL example
        p("\nPrepared by index example");

        Query query3 = session.createSQLQuery("SELECT * FROM users WHERE rating > ? LIMIT 0, 4 ;")
                .addEntity(User.class);
        query3.setDouble(0, 2.5);
        List<User> users3 = query3.list();
        p("Select by indexed params:");
        printUsers(new ArrayList<User>(users3));

    } catch (HibernateException ex) {
        System.err.println(ex);
    } finally {
        if (session != null)
            session.close();
    }
    p("end of SQL");
}

From source file:com.nec.harvest.service.impl.CashServiceImpl.java

License:Open Source License

/** {@inheritDoc} */
@Override// w  w w .j av  a2 s . c  o m
public boolean updateCashByOrgCodeAndDate(Session session, User user, JSONCash jSONCash, String monthly)
        throws ServiceException {
    if (user == null) {
        throw new IllegalArgumentException("user object must not be null or empty");
    }
    if (jSONCash == null) {
        throw new IllegalArgumentException("jSONCash must not be null or empty");
    }
    if (monthly == null) {
        throw new IllegalArgumentException("monthly must not be null or empty");
    }

    boolean isUpdated = Boolean.FALSE;
    try {
        Query query = repository.getNamedQuery(session, SqlConstants.SQL_UPDATE_CASH_BY_ORGANIZATION_AND_MONTH);
        query.setDouble("syokenHanbai", jSONCash.getSyokenHanbai());
        query.setDouble("prepaidHanbai", jSONCash.getPrepaidHanbai());
        query.setDouble("sonotaAzukari", jSONCash.getSonotaAzukari());
        query.setDouble("urikakeKaisyu", jSONCash.getUrikakeKaisyu());
        query.setDouble("kabusoku", jSONCash.getKabusoku());
        query.setDouble("soukingaku", jSONCash.getSoukingaku());
        query.setString("rem", jSONCash.getRem());

        // Logged-in user's code
        String userCode = user.getUsrCode();
        query.setString("tanCode", userCode);
        query.setString("APInf2", userCode);
        query.setString("stfCodeU", userCode);

        String version = null;
        try {
            Version productVersion = ProductHelper.getProductInfor();
            if (productVersion != null) {
                version = productVersion.getProjectVersion();
            }
        } catch (IOException ex) {
            // TODO
        }
        query.setString("prdNoU", version);
        query.setInteger("updNo", jSONCash.getUpdNo() + 1);
        query.setString("strCode", user.getOrganization().getStrCode());
        query.setString("getSudo", monthly);
        query.setDate("srDate", jSONCash.getSrDate());

        // Updating the record by using SQL for given changed information
        int numberOfRecordUpdated = query.executeUpdate();
        isUpdated = numberOfRecordUpdated > 0;
    } catch (HibernateException ex) {
        throw new ServiceException("An exception occured while update cash data ", ex);
    }
    return isUpdated;
}

From source file:com.nec.harvest.service.impl.InventoryServiceImpl.java

License:Open Source License

/** {@inheritDoc} */
@Override//ww  w .jav  a 2  s.  c  o  m
public boolean updateByOrgCodeAndMonthlyAndCtgCode(Session session, String strCode, String monthly,
        JSONInventory jsonInventory) throws ServiceException {
    if (StringUtils.isEmpty(strCode)) {
        throw new IllegalArgumentException("Organization must not be null or empty");
    }
    if (StringUtils.isEmpty(monthly)) {
        throw new IllegalArgumentException("Monthly must not be null or empty");
    }
    if (jsonInventory == null) {
        throw new IllegalArgumentException("Inventory must not be null or empty");
    }

    boolean isUpdated = Boolean.FALSE;
    try {
        StringBuilder sqlUpdate = new StringBuilder();
        sqlUpdate.append(" UPDATE Inventory c");
        sqlUpdate.append(" SET c.kingaku=:kingaku, ");
        sqlUpdate.append(
                " c.updNo = :newUpdNo, c.tanCode = :tanCode, c.APInf2 =:apInf2, c.stfCodeU = :stfCodeU, c.prdNoU = :prdNoU, c.timeU = NOW()");
        sqlUpdate.append(
                " WHERE c.pk.organization.strCode = :strCode AND c.pk.getSudo = :getSudo AND c.pk.category.ctgCode = :ctgCode");
        Query query = repository.getQuery(session, sqlUpdate.toString());

        String version = null;
        try {
            Version productVersion = ProductHelper.getProductInfor();
            if (productVersion != null) {
                version = productVersion.getProjectVersion();
            }
        } catch (IOException ex) {
            logger.warn(ex.getMessage(), ex);
        }
        query.setDouble("kingaku", jsonInventory.getKingaku());
        query.setInteger("newUpdNo", jsonInventory.getUpdNo() + 1);

        // 
        User user = AuthenticatedUserDetails.getUserPrincipal();
        query.setString("apInf2", user.getUsrCode());
        query.setString("tanCode", user.getUsrCode());
        query.setString("stfCodeU", user.getUsrCode());
        query.setString("prdNoU", version);
        query.setString("strCode", strCode);
        query.setString("getSudo", monthly);
        query.setString("ctgCode", jsonInventory.getCtgCode());

        int result = query.executeUpdate();
        isUpdated = result > 0;
    } catch (HibernateException ex) {
        throw new ServiceException("An exception occured while update inventory data ", ex);
    }
    return isUpdated;
}

From source file:com.nec.harvest.service.impl.PettyCashServiceImpl.java

License:Open Source License

/** {@inheritDoc} */
@Override/*from  w  w  w .  jav  a  2  s .  co  m*/
public void updatePettyCash(PettyCashBean pettyCashBean) throws ServiceException {
    if (pettyCashBean == null) {
        throw new IllegalArgumentException("Petty cash must not be null or empty");
    }

    User user = AuthenticatedUserDetails.getUserPrincipal();
    if (user == null) {
        logger.info("You must login to use this function");
        // 
        throw new IllegalArgumentException("You don't have a permission to use this");
    }

    float currentUpdNo = findUpdateNoById(pettyCashBean.getId());

    // ?\r\n\r\n?????????????
    // \r\n??????????
    if (currentUpdNo > pettyCashBean.getUpdNo()) {
        throw new IllegalArgumentException(
                "?\r\n\r\n?????????????"
                        + "\r\n??????????");
    }

    final Session session = HibernateSessionManager.getSession();
    Transaction tx = null;

    try {
        tx = session.beginTransaction();

        // 
        StringBuilder sql = new StringBuilder();
        sql.append(" UPDATE " + TblConstants.TBL_PETTY_CASH);
        sql.append(" SET SrDate=:srDate, CtgCode=:ctgCode, Naiyo=:naiyo, Kingaku=:kingaku, Shito=:shito, ");
        sql.append(
                " UpdNo=:updNo, TanCode=:tanCode, APInf2=:apInf2, StfCodeU=:stfCodeU, PrdNoU=:prdNoU, RecCkbn=1, TimeU=now()");
        sql.append(" WHERE RecID=:recId ");

        // 
        Query query = pettyCashRepository.getSQLQuery(session, sql.toString());

        query.setDate("srDate", pettyCashBean.getDate());
        query.setString("ctgCode", pettyCashBean.getItem());
        query.setString("naiyo", pettyCashBean.getContent());
        query.setDouble("kingaku", pettyCashBean.getAmount());
        query.setString("shito", pettyCashBean.getRemark());
        query.setFloat("updNo", currentUpdNo + 1);
        query.setString("tanCode", user.getUsrCode());
        query.setString("apInf2", user.getUsrCode());
        query.setString("stfCodeU", user.getUsrCode());

        try {
            query.setString("prdNoU", ProductHelper.getProductInfor().getVersion());
        } catch (IOException ex) {
            logger.warn(ex.getMessage(), ex);
        }

        query.setString("recId", pettyCashBean.getId());
        query.executeUpdate();
        tx.commit();
    } catch (SQLGrammarException | GenericJDBCException ex) {
        if (tx != null) {
            tx.rollback();
        }
        throw new ServiceException("Hibernate runtime exception occur when update a list of petty cashes", ex);
    } finally {
        tx = null;
        HibernateSessionManager.closeSession(session);
    }
}

From source file:com.netsteadfast.greenstep.base.dao.BaseDAO.java

License:Apache License

/**
 * for public QueryResult getList... doInHibernate
 * @param query       JPA-Style : from TB_ACCOUNT where account = ?0 
 * @param position   JPA-Style : "0", "1" .....
 * @param params/*w ww  .  java 2s  .co m*/
 */
@SuppressWarnings("rawtypes")
private void setQueryParams(Query query, String position, Object params) {
    if (params instanceof java.lang.String) {
        query.setString(position, (java.lang.String) params);
        return;
    }
    if (params instanceof java.lang.Character) {
        query.setCharacter(position, (java.lang.Character) params);
        return;
    }
    if (params instanceof java.lang.Double) {
        query.setDouble(position, (java.lang.Double) params);
        return;
    }
    if (params instanceof java.lang.Byte) {
        query.setByte(position, (java.lang.Byte) params);
        return;
    }
    if (params instanceof java.lang.Integer) {
        query.setInteger(position, (java.lang.Integer) params);
        return;
    }
    if (params instanceof java.lang.Long) {
        query.setLong(position, (java.lang.Long) params);
        return;
    }
    if (params instanceof java.lang.Boolean) {
        query.setBoolean(position, (java.lang.Boolean) params);
        return;
    }
    if (params instanceof java.math.BigDecimal) {
        query.setBigDecimal(position, (java.math.BigDecimal) params);
        return;
    }
    if (params instanceof java.util.Date) {
        query.setDate(position, (java.util.Date) params);
        return;
    }
    if (params instanceof java.util.List) {
        List listParams = (List) params;
        this.setQueryParamsOfList(query, position, listParams);
        return;
    }
}

From source file:com.nominanuda.hibernate.AbstractHibernateStructStore.java

License:Apache License

protected void bind(Query q, String k, Object v) {
    DataType t = struct.getDataType(v);// w  w  w  . j  av  a 2  s. com
    switch (t) {
    case array:
        q.setParameterList(k, struct.toMapsAndSetLists((DataArray) v));
        break;
    case object:
        q.setEntity(k, struct.toMapsAndSetLists((DataObject) v));
        break;
    case string:
        q.setString(k, (String) v);
        break;
    case bool:
        q.setBoolean(k, (Boolean) v);
        break;
    case number:
        Double d = ((Number) v).doubleValue();
        if (Maths.isInteger(d)) {
            q.setLong(k, d.longValue());
        } else {
            q.setDouble(k, d);
        }
        break;
    default:
        throw new IllegalArgumentException(t.name());
    }
}

From source file:com.qcadoo.model.internal.search.SearchQueryImpl.java

License:Open Source License

@Override
public void addParameters(final Query query) {
    for (Map.Entry<String, String> parameter : strings.entrySet()) {
        query.setString(parameter.getKey(), parameter.getValue());
    }//ww  w  .  j av a 2  s.  com
    for (Map.Entry<String, Boolean> parameter : booleans.entrySet()) {
        query.setBoolean(parameter.getKey(), parameter.getValue());
    }
    for (Map.Entry<String, Byte> parameter : bytes.entrySet()) {
        query.setByte(parameter.getKey(), parameter.getValue());
    }
    for (Map.Entry<String, Short> parameter : shorts.entrySet()) {
        query.setShort(parameter.getKey(), parameter.getValue());
    }
    for (Map.Entry<String, Integer> parameter : integers.entrySet()) {
        query.setInteger(parameter.getKey(), parameter.getValue());
    }
    for (Map.Entry<String, Long> parameter : longs.entrySet()) {
        query.setLong(parameter.getKey(), parameter.getValue());
    }
    for (Map.Entry<String, Float> parameter : floats.entrySet()) {
        query.setFloat(parameter.getKey(), parameter.getValue());
    }
    for (Map.Entry<String, Double> parameter : doubles.entrySet()) {
        query.setDouble(parameter.getKey(), parameter.getValue());
    }
    for (Map.Entry<String, BigDecimal> parameter : bigDecimals.entrySet()) {
        query.setBigDecimal(parameter.getKey(), parameter.getValue());
    }
    for (Map.Entry<String, Date> parameter : dates.entrySet()) {
        query.setDate(parameter.getKey(), parameter.getValue());
    }
    for (Map.Entry<String, Date> parameter : times.entrySet()) {
        query.setTime(parameter.getKey(), parameter.getValue());
    }
    for (Map.Entry<String, Date> parameter : timestamps.entrySet()) {
        query.setTimestamp(parameter.getKey(), parameter.getValue());
    }
    for (Map.Entry<String, Object> parameter : parameters.entrySet()) {
        query.setParameter(parameter.getKey(), parameter.getValue());
    }
    for (Map.Entry<String, Collection<? extends Object>> parametersList : parameterLists.entrySet()) {
        query.setParameterList(parametersList.getKey(), parametersList.getValue());
    }
    for (Map.Entry<String, Object> parameter : entities.entrySet()) {
        query.setEntity(parameter.getKey(), parameter.getValue());
    }
}

From source file:com.square.adherent.noyau.dao.implementations.contrat.ContratDaoImpl.java

License:Open Source License

@Override
@SuppressWarnings("unchecked")
public List<TypePayeurDto> getListeTypesPayeurs(TypePayeurCriteresDto criteres, Long idRoleGarantieAssure) {
    final StringBuffer requete = new StringBuffer(
            "select p.id, p.eid, p.libelle, b.bareme1Eid, b.bareme1Zone, b.bareme2Eid, b.bareme2Zone ");
    requete.append("from Contrat cg, Contrat cp, Garantie g, GarantieBareme b, TypePayeur p ");
    requete.append("where substring(cg.identifiantExterieur,1,13) = substring(cp.identifiantExterieur,1,13) ");
    requete.append("and g.contrat.id = cp.id ");
    requete.append("and g.id = b.garantie.id ");
    requete.append("and p.id = b.typePayeur.id ");
    requete.append("and g.role.id = :idRoleGarantieAssure ");
    if (criteres.getGarantieGestion() != null) {
        requete.append("and g.libelleGarantieGestion = :garantieGestion ");
    }/*from   ww  w.  j ava2  s .c  o  m*/
    if (criteres.getProduitGestion() != null) {
        requete.append("and g.libelleProduitGestion = :produitGestion ");
    }
    if (criteres.getContrat() != null) {
        requete.append("and cg.numeroContrat = :numeroContrat ");
    }
    if (criteres.getCodeTarif() != null) {
        requete.append("and g.codeTarif = :codeTarif ");
    }
    if (criteres.getMontantSouscrit() != null) {
        requete.append("and g.montantSouscrit = :montantSouscrit ");
    }
    if (criteres.getLibPopulation() != null) {
        requete.append("and g.libellePopulation = :libPopulation ");
    }
    requete.append(
            "group by p.id, p.eid, p.libelle, b.bareme1Eid, b.bareme1Zone, b.bareme2Eid, b.bareme2Zone ");

    final Query query = createQuery(requete.toString());
    query.setLong("idRoleGarantieAssure", idRoleGarantieAssure);
    if (criteres.getGarantieGestion() != null) {
        query.setString("garantieGestion", criteres.getGarantieGestion());
    }
    if (criteres.getProduitGestion() != null) {
        query.setString("produitGestion", criteres.getProduitGestion());
    }
    if (criteres.getContrat() != null) {
        query.setString("numeroContrat", criteres.getContrat());
    }
    if (criteres.getCodeTarif() != null) {
        query.setString("codeTarif", criteres.getCodeTarif());
    }
    if (criteres.getMontantSouscrit() != null) {
        query.setDouble("montantSouscrit", criteres.getMontantSouscrit());
    }
    if (criteres.getLibPopulation() != null) {
        query.setString("libPopulation", criteres.getLibPopulation());
    }

    final List<Object[]> rows = query.list();
    final List<TypePayeurDto> liste = new ArrayList<TypePayeurDto>();
    for (Object[] row : rows) {
        liste.add(new TypePayeurDto((Long) row[0], (String) row[1], (String) row[2], (String) row[3],
                (Integer) row[4], (String) row[5], (Integer) row[6]));
    }
    return liste;
}

From source file:de.innovationgate.webgate.api.jdbc.HibernateResultSet.java

License:Open Source License

public static void injectQueryParams(Query hibQuery, Map map) throws WGAPIException {

    if (map == null || map.size() == 0) {
        return;//ww  w.j av a 2  s  .  c om
    }

    String[] pNames = hibQuery.getNamedParameters();
    for (int i = 0; i < pNames.length; i++) {
        String pName = pNames[i];
        Object value = map.get(pName);
        if (value != null) {
            if (value instanceof WGDocument) {
                value = ((WGDocument) value).getNativeObject();
            }
            if (value instanceof Double) {
                hibQuery.setDouble(pName, (Double) value);
            } else if (value instanceof Collection<?>) {
                hibQuery.setParameterList(pName, (Collection<?>) value);
            } else {
                hibQuery.setParameter(pName, value);
            }
        }
    }

}