Example usage for org.hibernate Query setString

List of usage examples for org.hibernate Query setString

Introduction

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

Prototype

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

Source Link

Document

Bind a named String-valued parameter.

Usage

From source file:com.exilant.eGov.src.transactions.CommonMethodsImpl.java

License:Open Source License

/**
 * This API will return the sub feild id when the boundary num is passed. We are ordering by id_bndry_type desc so that sub
 * field value will come first.//from www  . j  av a  2s . co m
 */
@Override
public Integer getDivisionIdFromCode(final String divisionCode, final Connection connection) throws Exception {
    Integer divId = null;
    final String sql = "Select id_bndry from EG_BOUNDARY where BNDRY_NUM= ? and is_bndry_active=1 order by id_bndry_type desc";
    if (LOGGER.isInfoEnabled())
        LOGGER.info("Sub Field id query-->>>>>>>> " + sql);
    Query pst = persistenceService.getSession().createSQLQuery(sql);
    pst.setString(0, divisionCode);
    List<Object[]> rset = pst.list();
    for (final Object[] element : rset)
        divId = Integer.parseInt(element[0].toString());
    if (LOGGER.isInfoEnabled())
        LOGGER.info("Sub Feild id is >>>>>>>" + divId);
    return divId;
}

From source file:com.exilant.GLEngine.ChartOfAccounts.java

License:Open Source License

private void checkfuctreqd(final String glcode, final String fuctid, final DataCollection dc) throws Exception {

    final String sql = "select FUNCTIONREQD from chartofaccounts where glcode = ?";
    final Query pst = persistenceService.getSession().createSQLQuery(sql);
    pst.setString(0, glcode);
    List<Object[]> rs = null;
    rs = pst.list();//from   w ww. j  a v a  2 s . co  m
    for (final Object[] element : rs)
        if (Integer.parseInt(element[0].toString()) == 1)
            if (fuctid.length() > 0 && fuctid != null) {
                if (LOGGER.isInfoEnabled())
                    LOGGER.info("in COA33--" + fuctid);
            } else {
                dc.addMessage("exilError", "Select functionName for this glcode " + glcode);
                throw new TaskFailedException();

            }

}

From source file:com.exilant.GLEngine.ChartOfAccounts.java

License:Open Source License

private boolean updateInGL(final Transaxtion txnList[], final DataCollection dc)
        throws TaskFailedException, ParseException, SQLException {
    List<Object[]> resultset;
    CGeneralLedger gLedger = null;//from www . j a v a2 s . c  om
    ;
    CGeneralLedgerDetail gLedgerDet = null;
    EgRemittanceGldtl egRemitGldtl = null;
    // DataExtractor de=DataExtractor.getExtractor();
    final ArrayList glHeaderId = new ArrayList();
    final Transaxtion txn1 = txnList[0];
    final int VoucherHeaderId = Integer.parseInt(txn1.getVoucherHeaderId());
    if (LOGGER.isInfoEnabled())
        LOGGER.info("VoucherHeaderId----" + VoucherHeaderId);
    final String query = "select id from generalledger where voucherheaderid= ? order by id";
    Query pst = persistenceService.getSession().createSQLQuery(query);
    pst.setInteger(0, VoucherHeaderId);
    if (LOGGER.isInfoEnabled())
        LOGGER.info("select id from generalledger where voucherheaderid=" + VoucherHeaderId + " order by id");

    resultset = pst.list();
    int c = 0;
    for (final Object[] element : resultset) {

        glHeaderId.add(c, element[0].toString());
        c++;
    }

    final int count = glHeaderId.size();
    if (LOGGER.isInfoEnabled())
        LOGGER.info("count**********" + count);
    for (int k = 0; k < count; k++)
        try {
            final String delremitsql = "delete from eg_remittance_gldtl where gldtlid in (select id from generalledgerdetail where generalledgerid='"
                    + glHeaderId.get(k).toString() + "')";
            pst = persistenceService.getSession().createSQLQuery(delremitsql);
            pst.setString(0, glHeaderId.get(k).toString());
            if (LOGGER.isInfoEnabled())
                LOGGER.info("deleting remittance Query " + delremitsql);
            pst.executeUpdate();
            if (LOGGER.isInfoEnabled())
                LOGGER.info("delete from generalledgerdetail where generalledgerid='"
                        + glHeaderId.get(k).toString() + "'");
            final String delGenLedDet = "delete from generalledgerdetail where generalledgerid= ?";
            pst = persistenceService.getSession().createSQLQuery(delGenLedDet);
            pst.setString(0, glHeaderId.get(k).toString());
            final int del = pst.executeUpdate();
            if (del > 0)
                if (LOGGER.isInfoEnabled())
                    LOGGER.info("Records deleted from general ledger detail for GLH "
                            + glHeaderId.get(k).toString());
        } catch (final Exception e) {
            LOGGER.error("Exp in reading from generalledgerdetail: " + e, e);
            throw new TaskFailedException(e.getMessage());
        }

    if (count > 0)
        try {

            final String genLed = "DELETE FROM generalledger WHERE voucherheaderid= ?";
            pst = persistenceService.getSession().createSQLQuery(genLed);
            pst.setInteger(0, VoucherHeaderId);
            final int del = pst.executeUpdate();
            if (del > 0)
                if (LOGGER.isInfoEnabled())
                    LOGGER.info("DELETE FROM generalledger WHERE voucherheaderid=" + VoucherHeaderId);

        } catch (final Exception e) {
            if (LOGGER.isInfoEnabled())
                LOGGER.info("Exp in reading from generalledger: " + e, e);
        }

    for (final Transaxtion txn : txnList) {
        final GLAccount glAcc = (GLAccount) getGlAccountCodes().get(txn.getGlCode());
        gLedger = new CGeneralLedger();
        if (txn.getVoucherLineId() != null)
            gLedger.setVoucherlineId(Integer.parseInt(txn.getVoucherLineId()));
        CChartOfAccounts cChartOfAccounts = (CChartOfAccounts) persistenceService
                .find("from CChartOfAccounts where id=?", glAcc.getId());
        gLedger.setGlcodeId(cChartOfAccounts);
        gLedger.setGlcode(txn.getGlCode());
        gLedger.setDebitAmount(Double.parseDouble(txn.getDrAmount()));
        gLedger.setCreditAmount(Double.parseDouble(txn.getCrAmount()));
        gLedger.setDescription(txn.getNarration());
        CVoucherHeader cVoucherHeader = (CVoucherHeader) persistenceService
                .find("from CVoucherHeader where id=?", Long.parseLong(txn.getVoucherHeaderId()));
        gLedger.setVoucherHeaderId(cVoucherHeader);
        gLedger.setEffectiveDate(new Date());
        gLedger.setFunctionId(Integer.parseInt(txn.getFunctionId()));
        try {
            // if(LOGGER.isInfoEnabled())
            // LOGGER.info("inside the postin gl function before insert ----");
            generalLedgerPersistenceService.persist(gLedger);
        } catch (final Exception e) {
            if (LOGGER.isInfoEnabled())
                LOGGER.info("error in the gl++++++++++" + e, e);
            dc.addMessage("exilSQLError", e.toString());
            return false;
        }
        // if that code doesnot require any details no nedd to insert in GL
        // details
        if (glAcc.getGLParameters().size() <= 0)
            continue;
        final ArrayList glParamList = glAcc.getGLParameters();
        final ArrayList txnPrm = txn.getTransaxtionParam();
        String detKeyId = "";
        for (int a = 0; a < glParamList.size(); a++)
            try {
                // post the defaults set for details
                final GLParameter glPrm = (GLParameter) glParamList.get(a);
                /*
                 * if(!glPrm.getDetailKey().equalsIgnoreCase("0")&&glPrm.
                 * getDetailKey().length()>0){
                 * gLedgerDet.setGLId(String.valueOf(gLedger.getId()));
                 * gLedgerDet
                 * .setDetailTypeId(String.valueOf(glPrm.getDetailId()));
                 * gLedgerDet.setDetailKeyId(glPrm.getDetailKey());
                 * gLedgerDet.setDetailAmt(glPrm.getDetailAmt());
                 * gLedgerDet.insert(con); try {
                 * if(validRecoveryGlcode(gLedger.getglCodeId(),con) &&
                 * Double.parseDouble(gLedger.getcreditAmount())>0) {
                 * egRemitGldtl
                 * .setGldtlId(String.valueOf(gLedgerDet.getId()));
                 * egRemitGldtl.setGldtlAmt(gLedgerDet.getDetailAmt());
                 * if(glPrm.getTdsId()!=null)
                 * egRemitGldtl.setTdsId(glPrm.getTdsId());
                 * egRemitGldtl.insert(con); } } catch(Exception e) {
                 * LOGGER.
                 * error("Error while inserting to eg_remittance_gldtl "+e);
                 * return false; } }else
                 */ { // Post the details sent apart from defaults
                    for (int z = 0; z < txnPrm.size(); z++) {
                        final TransaxtionParameter tParam = (TransaxtionParameter) txnPrm.get(z);
                        if (tParam.getDetailName().equalsIgnoreCase(glPrm.getDetailName())
                                && tParam.getGlcodeId().equals(gLedger.getGlcodeId().getId().toString())) {
                            detKeyId = tParam.getDetailKey();
                            gLedgerDet = new CGeneralLedgerDetail();
                            gLedgerDet.setGeneralLedgerId(gLedger);
                            Accountdetailtype acctype = (Accountdetailtype) persistenceService
                                    .find("from Accountdetailtype where id=?", glPrm.getDetailId());
                            gLedgerDet.setDetailTypeId(acctype);
                            gLedgerDet.setDetailKeyId(Integer.parseInt(detKeyId));
                            gLedgerDet.setAmount(new BigDecimal(tParam.getDetailAmt()));
                            generalLedgerDetPersistenceService.persist(gLedgerDet);
                            try {
                                if (validRecoveryGlcode(String.valueOf(gLedger.getGlcodeId().getId()))
                                        && gLedger.getCreditAmount() > 0) {
                                    egRemitGldtl = new EgRemittanceGldtl();
                                    if (LOGGER.isDebugEnabled())
                                        LOGGER.debug("----------" + gLedger.getGlcode());
                                    egRemitGldtl.setGeneralledgerdetail(gLedgerDet);
                                    egRemitGldtl.setGldtlamt(gLedgerDet.getAmount());
                                    Recovery tdsentry = null;
                                    if (tParam.getTdsId() != null)
                                        tdsentry = (Recovery) persistenceService.find(
                                                "from Recovery where id=?", Long.parseLong(tParam.getTdsId()));
                                    egRemitGldtl.setRecovery(tdsentry);
                                    remitanceDetPersistenceService.persist(egRemitGldtl);
                                }
                            } catch (final Exception e) {
                                LOGGER.error("Error while inserting to eg_remittance_gldtl " + e, e);
                                return false;
                            }
                        }
                    }
                }
                // post the gldetailid, gldtlamt to eg_remittance_gldtl
                // table
                /*
                 * try { if(validRecoveryGlcode(gLedger.getglCodeId(),con)
                 * && Double.parseDouble(gLedger.getcreditAmount())>0) {
                 * egRemitGldtl
                 * .setGldtlId(String.valueOf(gLedgerDet.getId()));
                 * egRemitGldtl.setGldtlAmt(gLedgerDet.getDetailAmt());
                 * egRemitGldtl.insert(con); } } catch(Exception e) {
                 * LOGGER.
                 * error("Error while inserting to eg_remittance_gldtl "+e);
                 * return false; }
                 */
            } catch (final Exception e) {
                LOGGER.error("Inside updateInGl" + e.getMessage(), e);
                throw new TaskFailedException();
            }
    }
    // if(LOGGER.isInfoEnabled()) LOGGER.info("HI- 396-6");// TBR
    return true;
}

From source file:com.farmafene.aurius.dao.DiccionarioFactoryImpl.java

License:Open Source License

/**
 * {@inheritDoc}/*from w w w  . j  a  v a2 s  .co m*/
 * 
 * @see com.farmafene.aurius.core.IDiccionarioFactory#getServicio(java.lang.String)
 */
public Servicio getServicio(String id) throws IllegalArgumentException {

    if (logger.isDebugEnabled()) {
        logger.debug("getServicio(" + id + ")");
    }
    String grupo = FormatUtil.getAplicacionFromIdServicio(id);
    BigDecimal svr_id = new BigDecimal(FormatUtil.getOperacionFromIdServicio(id));

    Session sess = null;
    ServicioSvr svr = null;
    SessionFactory sf = DiccionarioSessionFactory.getSessionFactory();
    sess = sf.getCurrentSession();
    Query q = sess.createQuery("select s from ServicioSvr s,ServicioDesc d where " + "s.id.grupo = d.id.grupo"
            + " and s.id.id = d.id.id" + " and s.id.version = d.version"
            + " and d.id.grupo=:grupo and d.id.id=:id");
    q.setString("grupo", grupo);
    q.setBigDecimal("id", svr_id);
    if (logger.isDebugEnabled()) {
        logger.debug("getServicio(): Begin Query");
    }
    svr = (ServicioSvr) q.uniqueResult();
    if (svr != null) {
        svr.getDescripcion().getRoles();
        if (logger.isDebugEnabled()) {
            logger.debug("getServicio(): End Query");
        }
    }
    return getServicioFromServicioSvr(svr);

}

From source file:com.fiveamsolutions.nci.commons.audit.AuditLogRecordSearchCriteria.java

License:Open Source License

private Query helpBuildQuery(Session session, StringBuffer query, String orderByProperty) {
    if (id != null) {
        query.append(String.format(" %s.entityId = :entityId OR ", ROOT_ALIAS));
        query.append(String.format("  (ald in elements(%s.details) ", ROOT_ALIAS));
        query.append("    AND (ald.oldValue = :entityIdStr OR ald.newValue = :entityIdStr)) ");
    } else {//from   w  w  w. j  a v  a 2  s.c  om
        query.append(String.format(" %s.transactionId in (:transactionIds) ", ROOT_ALIAS));
    }

    query.append(orderByProperty);
    Query q = session.createQuery(query.toString());

    if (id != null) {
        q.setLong("entityId", getId());
        q.setString("entityIdStr", Long.toString(getId()));
    } else {
        q.setParameterList("transactionIds", getTransactionId());
    }

    return q;
}

From source file:com.fiveamsolutions.nci.commons.authentication.AttemptLoggingLoginModule.java

License:Open Source License

/**
* {@inheritDoc}/*from w  w  w . j  av a  2 s .  co  m*/
*/
@SuppressWarnings("PMD.PreserveStackTrace")
public boolean login() throws LoginException {
    LOG.trace("login()");
    NameCallback nameCallback = new NameCallback("Username: ");

    try {
        callbackHandler.handle(new Callback[] { nameCallback });
    } catch (IOException e) {
        LOG.warn(e.getMessage(), e);
        throw new LoginException("Unable to handle callbacks: " + e.getMessage());
    } catch (UnsupportedCallbackException e) {
        LOG.warn(e.getMessage(), e);
        throw new LoginException("Unable to handle callbacks: " + e.getMessage());
    }

    Session s = getHibernateHelper().getSessionFactory().openSession();
    Transaction tx = s.beginTransaction();
    try {
        Query query = s.createQuery("select user from " + AbstractUser.class.getName()
                + " user where lower(username) = lower(:username)");
        query.setString("username", nameCallback.getName());
        AbstractUser user = (AbstractUser) query.uniqueResult();
        if (user != null) {
            LoginAttempt la = new LoginAttempt();
            la.setUser(user);
            la.setDate(new Date());
            la.setSuccessful(sharedState.get(CommonLoginModule.JBOSS_PASSWORD_STACKING_USER_PARAM) != null);
            s.save(la);
        }
    } finally {
        tx.commit();
        s.close();
    }

    return true;
}

From source file:com.fiveamsolutions.nci.commons.authentication.CommonLoginModule.java

License:Open Source License

/**
 * {@inheritDoc}//from w ww.  j a  v  a2  s  .  co  m
 */
@SuppressWarnings({ "unchecked", "PMD.PreserveStackTrace" }) // LoginException can't take a cause
public boolean login() throws LoginException {
    LOG.trace("login()");
    NameCallback nameCallback = new NameCallback("Username: ");
    PasswordCallback passwordCallback = new PasswordCallback("Password: ", false);
    Callback[] callbacks = new Callback[2];
    callbacks[0] = nameCallback;
    callbacks[1] = passwordCallback;

    try {
        callbackHandler.handle(callbacks);
    } catch (IOException e) {
        LOG.warn(e.getMessage(), e);
        throw new LoginException("Unable to handle callbacks: " + e.getMessage());
    } catch (UnsupportedCallbackException e) {
        LOG.warn(e.getMessage(), e);
        throw new LoginException("Unable to handle callbacks: " + e.getMessage());
    }

    String username = nameCallback.getName();
    char[] password = passwordCallback.getPassword();

    // Do the hibernate manipulation directly, rather than via a service call (we're outside the OSIV filter)
    Session s = getHibernateHelper().getSessionFactory().openSession();
    try {
        Query query = s.createQuery(
                "SELECT username, password, passwordExpirationDate " + " FROM " + AbstractUser.class.getName()
                        + " WHERE lower(username) = lower(:username) and status = :active");
        query.setString("username", username);
        query.setString("active", AccountStatus.ACTIVE.name());
        Object[] user = (Object[]) query.uniqueResult();
        if (user == null || !SecurityUtils.matches((Password) user[1], new String(password))) {
            throw new FailedLoginException("Unknown user and/or bad password");
        }

        checkExpirationDate((Date) user[2]);

        name = (String) user[0];
    } finally {
        s.close();
    }

    // These are the two options JBoss will look for with the useFirstPass option
    ((Map<String, Object>) sharedState).put(JBOSS_PASSWORD_STACKING_USER_PARAM, name);
    ((Map<String, Object>) sharedState).put(JBOSS_PASSWORD_STACKING_PASSWORD_PARAM, password);

    return true; // this module should never be ignored
}

From source file:com.flexcore.dao_orm.ClienteDAO.java

@Override
public List<Clientefisico> verClientesFisicosPaginadosBusqueda(int pagina, String entrada) throws Exception {

    int datoInicial = (pagina - 1) * 10;
    int datoFinal = pagina * 10;

    Transaction trans = session.beginTransaction();

    Query q = session.createSQLQuery(" { call obtenerClientesFisicosBusquedaPaginado(?,?,?) }")
            .setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
    q.setInteger(0, datoInicial);//from   w ww .j  a v  a  2s.  c  o m
    q.setInteger(1, datoFinal);
    q.setString(2, entrada);
    q.executeUpdate();

    List<Clientefisico> listaClienteFisicos = q.list();
    trans.commit();
    session.close();

    return listaClienteFisicos;
}

From source file:com.flexcore.dao_orm.ClienteDAO.java

@Override
public List<Clientejuridico> verClientesJuridicosPaginadosBusqueda(int pagina, String entrada)
        throws Exception {
    int datoInicial = (pagina - 1) * 10;
    int datoFinal = pagina * 10;
    Transaction trans = session.beginTransaction();

    Query q = session.createSQLQuery(" { call obtenerClientesJuridicosBusquedaPaginado(?,?,?) }")
            .setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
    q.setInteger(0, datoInicial);/*www.j av a 2 s .c  om*/
    q.setInteger(1, datoFinal);
    q.setString(2, entrada);
    q.executeUpdate();

    List<Clientejuridico> listaClienteJuridicos = q.list();

    trans.commit();
    session.close();

    return listaClienteJuridicos;
}

From source file:com.flexcore.dao_orm.ClienteDAO.java

@Override
public int obtenerCantidadClientesFisicosBusqueda(String entrada) throws Exception {
    int cantidadClientes = 0;
    Transaction trans = session.beginTransaction();
    Query q = session.createSQLQuery(" { call obtenerCantidadClientesFisicosBusqueda (?) }");
    q.setString(0, entrada); // first parameter, index starts with 0
    q.executeUpdate();/*www  . j  av a2s . c  o  m*/
    System.out.println("Obteniendo cantidad cliente Fisico");
    System.out.println(q.list().get(0).toString());
    cantidadClientes = Integer.parseInt(q.list().get(0).toString());
    trans.commit();
    session.close();

    return cantidadClientes;
}