Example usage for org.hibernate Query uniqueResult

List of usage examples for org.hibernate Query uniqueResult

Introduction

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

Prototype

R uniqueResult();

Source Link

Document

Convenience method to return a single instance that matches the query, or null if the query returns no results.

Usage

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

/**
 * Comprueba que un email no est en la base de datos
 *
 * @param email/*  w w w . j a v  a2s  . c  o m*/
 * @return true si existe el email
 */
public boolean comprobarEmail(String email) {
    logger.info("comprobar");
    boolean existe = false;
    Session sesion = HibernateUtil.getSessionFactory().openSession();
    Query qu = sesion.createQuery("Select U.login from Usuario U where U.login=:email").setString("email",
            email);
    Object salida = qu.uniqueResult();

    if (salida != null) {
        existe = true;
    }
    sesion.flush();
    sesion.close();
    logger.info("fin comprobar " + existe);
    return existe;
}

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

/**
 * Comprueba que el login es correcto//from w w  w.j a  v  a  2 s  .c o  m
 *
 * @param usuario
 * @return usuario logeado
 */
public Usuario comprobarLogin(Usuario usuario) {
    Usuario user = null;
    Session sesion = HibernateUtil.getSessionFactory().openSession();
    try {

        Query qu = sesion.createQuery("Select u from Usuario u where u.login=:email AND u.password=:clave")
                .setString("email", usuario.getLogin()).setString("clave", usuario.getPassword());//OJO
        Object salida = qu.uniqueResult();
        if (salida != null) {
            user = (Usuario) salida;

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

    sesion.flush();
    sesion.close();
    return user;

}

From source file:com.atlanta.educati.daoImp.ApoderadoDaoImp.java

@Override
public Object consultUnique(String consulta) {
    Session sesion = sesionFactory.openSession();
    sesion.beginTransaction().commit();//  w  ww  . j  ava  2  s. c o m

    Query query = sesion.createQuery(consulta);
    Object objeto = query.uniqueResult();

    sesion.close();

    return objeto;
}

From source file:com.autobizlogic.abl.logic.dynamic.DatabaseClassManager.java

License:Open Source License

private boolean checkForUpdateHibernate() {
    try {/*from  www .  ja v  a2s . co m*/
        SessionFactory sessFact = cfg.buildSessionFactory();
        Session session = sessFact.getCurrentSession();
        Transaction tx = session.beginTransaction();

        Query query = session.createQuery("from Project where name = :name").setString("name", projectName);
        Project project = (Project) query.uniqueResult();

        LogicFileLog fileLog = loadClassesFromProject(project);
        if (fileLog == null) {
            tx.commit();
            return false;
        }
        session.save(fileLog);

        tx.commit();
        return true;
    } catch (Exception ex) {
        log.error("Unable to check for logic update", ex);
        return false;
    }
}

From source file:com.autobizlogic.abl.logic.dynamic.Deployer.java

License:Open Source License

/**
 * Deploy a jar into a database for use by DatabaseClassManager.
 * @param props Should contain the required parameters:
 * <ul>/*from  w w w  .java  2 s.c o  m*/
 * <li>either HIB_CFG_FILE (Hibernate config file path as a string) or 
 * HIB_CFG as a Hibernate Configuration object
 * <li>PROJECT_NAME: the name of the project to deploy to (will be created if it does not exist)
 * <li>JAR_FILE_NAME: the path of the jar file to deploy, as a String
 * <li>EFFECTIVE_DATE: the date/time at which the new logic classes should take effect, 
 * as a java.util.Date (optional)
 * </ul>
 * @return Null if everything went OK, otherwise a reason for the failure
 */
public static String deploy(Properties props) {

    Logger root = Logger.getRootLogger();
    root.addAppender(new ConsoleAppender(new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN)));
    Logger.getLogger("org.hibernate").setLevel(Level.WARN);
    Logger.getLogger("org.hibernate.tool.hbm2ddl").setLevel(Level.DEBUG);
    Logger.getLogger("org.hibernate.SQL").setLevel(Level.DEBUG);
    Logger.getLogger("org.hibernate.transaction").setLevel(Level.DEBUG);

    Configuration config;
    if (props.get(HIB_CFG) == null) {
        config = new Configuration();
        File cfgFile = new File((String) props.get(HIB_CFG_FILE));
        config.configure(cfgFile);
    } else
        config = (Configuration) props.get(HIB_CFG);

    if (config.getClassMapping(Project.class.getName()) == null) {
        config.addAnnotatedClass(Project.class);
        config.addAnnotatedClass(LogicFile.class);
        config.addAnnotatedClass(LogicFileLog.class);
    }

    SessionFactory sessFact = config.buildSessionFactory();
    Session session = sessFact.getCurrentSession();
    Transaction tx = session.beginTransaction();

    Query query = session.createQuery("from Project where name = :name").setString("name",
            (String) props.get(PROJECT_NAME));
    Project project = (Project) query.uniqueResult();
    if (project == null) {
        project = new Project();
        project.setName((String) props.get(PROJECT_NAME));
        session.save(project);
    }

    LogicFile logicFile = new LogicFile();
    String fileName = (String) props.get(JAR_FILE_NAME);
    String shortFileName = fileName;
    if (fileName.length() > 300)
        shortFileName = fileName.substring(0, 300);
    logicFile.setName(shortFileName);
    logicFile.setCreationDate(new Timestamp(System.currentTimeMillis()));
    File jarFile = new File((String) props.get(JAR_FILE_NAME));
    try {
        FileInputStream inStr = new FileInputStream(fileName);
        Blob blob = session.getLobHelper().createBlob(inStr, jarFile.length());
        logicFile.setContent(blob);
    } catch (Exception ex) {
        throw new RuntimeException("Error while storing jar file into database", ex);
    }
    Date effDate = (Date) props.get(EFFECTIVE_DATE);
    logicFile.setEffectiveDate(new Timestamp(effDate.getTime()));
    logicFile.setProject(project);
    session.save(logicFile);

    tx.commit();
    sessFact.close();

    return null;
}

From source file:com.autobizlogic.abl.rule.MinMaxRule.java

License:Open Source License

/**
 * When there is no other way, we have to issue a SQL to figure out the new min/max value.
 *//*from   ww w .j a  v  a2 s  .c  om*/
/*private*/ void sqlRecompute(PersistentBean bean, LogicTransactionContext context) {

    String minMax = "max";
    if (type == MinMaxType.MIN)
        minMax = "min";
    String sql = "select " + minMax + "(" + getWatchedFieldName() + ") from "
            + getRole().getOtherMetaEntity().getEntityName() + " where "
            + getRole().getOtherMetaRole().getRoleName() + " = :parent";
    if (getQualificationSQL() != null)
        sql += " and (" + getQualificationSQL() + ")";
    Query query = context.getSession().createQuery(sql);
    query.setEntity("parent", bean.getEntity());
    Object result = query.uniqueResult();
    Class<?> attType = bean.getMetaEntity().getMetaAttribute(getBeanAttributeName()).getType();
    Number newMax = NumberUtil.convertNumberToType((Number) result, attType);
    bean.put(getBeanAttributeName(), newMax);
}

From source file:com.bac.accountserviceapp.data.mysql.MysqlAccountAccessor.java

private ApplicationAccountEntityProxy getEntityBySecondaryKey(ApplicationAccountEntityProxy entity)
        throws HibernateException {

    Objects.requireNonNull(sessionFactory, uninitialized);
    Objects.requireNonNull(entity, nullParameter);
    String queryName = entity.getSecondaryKeyQueryName();
    if (queryName == null || queryName.isEmpty()) {
        return null;
    }/*  w ww .  j  a  v  a2 s.  c  o  m*/
    ApplicationAccountEntityProxy proxy = null;
    session = sessionFactory.getCurrentSession();
    Transaction transaction = session.beginTransaction();
    try {
        Query query = session.getNamedQuery(queryName);
        entity.setSecondaryKeyQuery(query);
        proxy = (ApplicationAccountEntityProxy) query.uniqueResult();
        transaction.commit();
    } catch (HibernateException e) {
        transaction.rollback();
        logger.error("Retrieve entity by secondary key", e);
        throw (e);
    }
    return proxy;
}

From source file:com.bancomat.springmvc.dao.UtenteDao.java

public static Utente getUtente(int id, int pin) {
    Utente utente = null;/*from  w ww .jav a  2 s . co m*/
    session = HibernateUtil.getSessionFactory().openSession();
    Transaction tsc = session.beginTransaction();

    Query qry = session.createQuery("from Utente where idUtente = :id and pin = :pin");
    qry.setInteger("id", id);
    qry.setInteger("pin", pin);
    utente = (Utente) qry.uniqueResult();

    return utente;
}

From source file:com.bancomat.springmvc.dao.UtenteDao.java

public static double getSaldo(int id) {
    session = HibernateUtil.getSessionFactory().openSession();
    Transaction tsc = session.beginTransaction();
    Double saldo;//w ww . java2  s .  c o  m
    String selectAll = "select u.saldo from Utente u where idUtente = :id";

    Query qry = session.createQuery(selectAll);
    qry.setInteger("id", id);

    saldo = (Double) qry.uniqueResult();

    return saldo;
}

From source file:com.bancomat.springmvc.dao.UtenteDao.java

public static boolean isUtente(int id) {
    session = HibernateUtil.getSessionFactory().openSession();
    Transaction tsc = session.beginTransaction();
    Query qry = session.createQuery("from Utente where idUtente = :id");
    qry.setInteger("id", id);
    if (qry.uniqueResult() != null) {
        return true;
    } else {/*from   w  ww . jav  a 2 s  .  co  m*/
        return false;
    }

}