Example usage for org.hibernate Query setInteger

List of usage examples for org.hibernate Query setInteger

Introduction

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

Prototype

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

Source Link

Document

Bind a named int-valued parameter.

Usage

From source file:com.esteban.cmms.maven.model.Roles_Model.java

public Object getRolesById(Integer id) {
    Object obj = null;// ww w.ja  v a 2 s  .  c o  m
    Transaction trns = null;
    Session session = HibernateUtil.getSessionFactory().openSession();
    try {
        trns = session.beginTransaction();
        String queryString = "from Roles " + " where Id = :id";
        Query query = session.createQuery(queryString);
        query.setInteger("id", id);
        obj = query.uniqueResult();
    } catch (RuntimeException e) {
        e.printStackTrace();
    } finally {
        session.flush();
        session.close();
    }
    return obj;
}

From source file:com.esteban.cmms.maven.model.Secciones_Model.java

/**
 * Obtiene un nico registro de la base de datos en la tabla secciones
 * @param objid entero correspondiente al id del registro en la base de datos
 * @return un nico resultado tipo Secciones con los datos del registro.
 *///from  w ww  .  j  a  v  a 2  s.  co  m
public Secciones getSeccionById(int objid) {
    Secciones obj = null;
    Transaction trns = null;
    Session session = HibernateUtil.getSessionFactory().openSession();
    try {
        trns = session.beginTransaction();
        String queryString = "from Secciones where id = :id";
        Query query = session.createQuery(queryString);
        query.setInteger("id", objid);
        obj = (Secciones) query.uniqueResult();
    } catch (RuntimeException e) {
        e.printStackTrace();
    } finally {
        session.flush();
        session.close();
    }
    return obj;
}

From source file:com.esteban.cmms.maven.model.TiposMaquinas_Model.java

/**
 * Obtiene un nico registro de la base de datos en la tabla tiposMaquinas
 *
 * @param objid entero correspondiente al id del registro en la base de
 * datos/*from ww  w  .ja v  a 2 s . c om*/
 * @return un nico resultado tiposMaquinas con los datos del registro.
 */
public TiposMaquinas getTipoMaquinaById(int tipomid) {
    TiposMaquinas tipom = null;
    Transaction trns = null;
    Session session = HibernateUtil.getSessionFactory().openSession();
    try {
        trns = session.beginTransaction();
        String queryString = "from TiposMaquinas where id = :id";
        Query query = session.createQuery(queryString);
        query.setInteger("id", tipomid);
        tipom = (TiposMaquinas) query.uniqueResult();
    } catch (RuntimeException e) {
        e.printStackTrace();
    } finally {
        session.flush();
        session.close();
    }
    return tipom;
}

From source file:com.esteban.cmms.maven.model.Usuarios_Model.java

/**
 * Veta los usuarios en el sistema para que no tengan ms acceso al mismo
 *
 * @param estado Estado que se le asigna el usuario 'Activo' o 'Vetado'
 * @param id entero correspondiente al registro en la base de datos
 *//*from  ww  w.  java2  s .  co m*/
public void vetarUsuario(String estado, Integer id) {
    Transaction trns = null;
    Session session = HibernateUtil.getSessionFactory().openSession();
    try {
        trns = session.beginTransaction();
        Query query = session.createQuery("UPDATE Usuarios " + "SET Estado = :estado " + "WHERE Id = :id");
        query.setString("estado", estado);
        query.setInteger("id", id);
        query.executeUpdate();
        session.getTransaction().commit();
    } catch (RuntimeException e) {
        if (trns != null) {
            trns.rollback();
        }
        e.printStackTrace();
    } finally {
        session.flush();
        session.close();
    }
}

From source file:com.esteban.cmms.maven.model.Usuarios_Model.java

/**
 *Obtiene un registro de la tabla usuarios con todos sus datos
 * @param objid un entero para encontrar un nico registro que corresponda
 * @return si corresponde, un objeto usuarios con la informacin
 *//*from   w  w  w  . j a  v  a2  s .  c  o  m*/
public Usuarios getUsuarioById(int objid) {
    Usuarios obj = null;
    Transaction trns = null;
    Session session = HibernateUtil.getSessionFactory().openSession();
    try {
        trns = session.beginTransaction();
        String queryString = "from Usuarios as users" + " left join fetch users.roles"
                + " where users.id = :id";
        Query query = session.createQuery(queryString);
        query.setInteger("id", objid);
        obj = (Usuarios) query.uniqueResult();
    } catch (RuntimeException e) {
        e.printStackTrace();
    } finally {
        session.flush();
        session.close();
    }
    return obj;
}

From source file:com.esteban.cmms.maven.model.Vendedores_Model.java

/**
 * Obtiene un nico registro de la base de datos en la tabla vendedores
 *
 * @param objid entero correspondiente al id del registro en la base de
 * datos/*from w w  w. j a  va2  s .  co  m*/
 * @return un nico resultado tipo Vendedores con los datos del registro.
 */
public Vendedores getVendedorById(int objid) {
    Vendedores obj = null;
    Transaction trns = null;
    Session session = HibernateUtil.getSessionFactory().openSession();
    try {
        trns = session.beginTransaction();
        String queryString = "from Vendedores where id = :id";
        Query query = session.createQuery(queryString);
        query.setInteger("id", objid);
        obj = (Vendedores) query.uniqueResult();
    } catch (RuntimeException e) {
        e.printStackTrace();
    } finally {
        session.flush();
        session.close();
    }
    return obj;
}

From source file:com.eurodyn.uns.dao.hibernate.HibernateUserDao.java

License:Mozilla Public License

public User findUser(Integer id) throws DAOException {
    User user = null;/*from w w  w. j  a  v  a  2  s .  c o  m*/
    Session session = null;
    try {
        session = getSession();
        Query query = session.createQuery("select u from User as u where u.id=:userId");
        query.setInteger("userId", id.intValue());
        List list = query.list();
        if (list.size() > 0) {
            user = (User) list.get(0);
            Hibernate.initialize(user.getDeliveryAddresses());
        }
    } catch (HibernateException e) {
        throw new DAOException(e);
    }
    return user;
}

From source file:com.evolveum.midpoint.repo.sql.helpers.CertificationCaseHelper.java

License:Apache License

protected List<Long> addOrDeleteCases(Session session, String campaignOid,
        Collection<? extends ItemDelta> modifications) throws SchemaException, DtoTranslationException {
    final ItemPath casePath = new ItemPath(AccessCertificationCampaignType.F_CASE);
    boolean replacePresent = false;
    List<Long> affectedIds = new ArrayList<>();
    for (ItemDelta delta : modifications) {
        ItemPath deltaPath = delta.getPath();
        if (!casePath.isSubPathOrEquivalent(deltaPath)) {
            throw new IllegalStateException("Wrong campaign delta sneaked into updateCampaignCases: class="
                    + delta.getClass() + ", path=" + deltaPath);
        }// ww w .ja v a2 s . c o  m

        if (deltaPath.size() == 1) {
            if (delta.getValuesToDelete() != null) {
                // todo do 'bulk' delete like delete from ... where oid=? and id in (...)
                for (PrismContainerValue value : (Collection<PrismContainerValue>) delta.getValuesToDelete()) {
                    Long id = value.getId();
                    if (id == null) {
                        throw new SchemaException("Couldn't delete certification case with null id");
                    }
                    affectedIds.add(id);
                    // TODO couldn't this cascading be done by hibernate itself?
                    Integer integerCaseId = RUtil.toInteger(id);
                    Query deleteCaseDecisions = session.getNamedQuery("delete.campaignCaseDecisions");
                    deleteCaseDecisions.setString("oid", campaignOid);
                    deleteCaseDecisions.setInteger("id", integerCaseId);
                    deleteCaseDecisions.executeUpdate();
                    Query deleteCaseReferences = session.createSQLQuery("delete from "
                            + RCertCaseReference.TABLE + " where owner_owner_oid=:oid and owner_id=:id");
                    deleteCaseReferences.setString("oid", campaignOid);
                    deleteCaseReferences.setInteger("id", integerCaseId);
                    deleteCaseReferences.executeUpdate();
                    Query deleteCase = session.getNamedQuery("delete.campaignCase");
                    deleteCase.setString("oid", campaignOid);
                    deleteCase.setInteger("id", integerCaseId);
                    deleteCase.executeUpdate();
                }
            }
            // TODO generated IDs might conflict with client-provided ones
            // also, client-provided IDs might conflict with those that are already in the database
            // So it's safest not to provide any IDs by the client
            if (delta.getValuesToAdd() != null) {
                int currentId = generalHelper.findLastIdInRepo(session, campaignOid, "get.campaignCaseLastId")
                        + 1;
                addCertificationCampaignCases(session, campaignOid, delta.getValuesToAdd(), currentId,
                        affectedIds);
            }
            if (delta.getValuesToReplace() != null) {
                deleteCertificationCampaignCases(session, campaignOid);
                addCertificationCampaignCases(session, campaignOid, delta.getValuesToReplace(), 1, affectedIds);
                replacePresent = true;
            }

        }
    }
    return replacePresent ? null : affectedIds;
}

From source file:com.evolveum.midpoint.repo.sql.helpers.CertificationCaseHelper.java

License:Apache License

private void updateCasesContent(Session session, String campaignOid,
        Collection<? extends ItemDelta> modifications, List<Long> casesAddedOrDeleted,
        RepoModifyOptions modifyOptions)
        throws SchemaException, ObjectNotFoundException, DtoTranslationException {
    Set<Long> casesModified = new HashSet<>();
    for (ItemDelta delta : modifications) {
        ItemPath deltaPath = delta.getPath();
        if (deltaPath.size() > 1) {
            LOGGER.trace("Updating campaign " + campaignOid + " with delta " + delta);

            // should start with "case[id]"
            long id = checkPathSanity(deltaPath, casesAddedOrDeleted);

            Query query = session.getNamedQuery("get.campaignCase");
            query.setString("ownerOid", campaignOid);
            query.setInteger("id", (int) id);

            byte[] fullObject = (byte[]) query.uniqueResult();
            if (fullObject == null) {
                throw new ObjectNotFoundException("Couldn't update cert campaign " + campaignOid
                        + " + by delta with path " + deltaPath + " - specified case does not exist");
            }//w  w w  . j  a v  a 2  s  . c o m
            AccessCertificationCaseType aCase = RAccessCertificationCase.createJaxb(fullObject, prismContext,
                    false);

            delta = delta.clone(); // to avoid changing original modifications
            delta.setParentPath(delta.getParentPath().tail(2)); // remove "case[id]" from the delta path
            delta.applyTo(aCase.asPrismContainerValue());

            // we need to generate IDs but we (currently) do not use that for setting "isTransient" flag
            PrismIdentifierGenerator generator = new PrismIdentifierGenerator();
            generator.generate(aCase, PrismIdentifierGenerator.Operation.MODIFY);

            RAccessCertificationCase rCase = RAccessCertificationCase.toRepo(campaignOid, aCase, prismContext);
            session.merge(rCase);

            LOGGER.trace("Access certification case {} merged", rCase);
            casesModified.add(aCase.getId());
        }
    }

    // refresh campaign cases, if requested
    if (RepoModifyOptions.isExecuteIfNoChanges(modifyOptions)) {
        Query query = session.getNamedQuery("get.campaignCases");
        query.setString("ownerOid", campaignOid);
        List<Object> cases = query.list();
        for (Object o : cases) {
            if (!(o instanceof byte[])) {
                throw new IllegalStateException("Certification case: expected byte[], got " + o.getClass());
            }
            byte[] fullObject = (byte[]) o;
            AccessCertificationCaseType aCase = RAccessCertificationCase.createJaxb(fullObject, prismContext,
                    false);
            Long id = aCase.getId();
            if (id != null && casesAddedOrDeleted != null && !casesAddedOrDeleted.contains(id)
                    && !casesModified.contains(id)) {
                RAccessCertificationCase rCase = RAccessCertificationCase.toRepo(campaignOid, aCase,
                        prismContext);
                session.merge(rCase);
                LOGGER.trace("Access certification case {} refreshed", rCase);
            }
        }
    }
}

From source file:com.evolveum.midpoint.repo.sql.helpers.LookupTableHelper.java

License:Apache License

private void deleteRowById(Session session, String tableOid, Long id) {
    Query query = session.getNamedQuery("delete.lookupTableDataRow");
    query.setString("oid", tableOid);
    query.setInteger("id", RUtil.toInteger(id));
    query.executeUpdate();//  w w  w .j  ava  2 s . c o m
}