Example usage for org.hibernate SQLQuery uniqueResult

List of usage examples for org.hibernate SQLQuery uniqueResult

Introduction

In this page you can find the example usage for org.hibernate SQLQuery 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:kp.logic.GeneralMethods.java

public Date getSysDate(Session session) {
    SQLQuery query = session.createSQLQuery("select sysdate  from dual");
    Logger.getLogger(GeneralMethods.class.getName()).log(Level.SEVERE,
            "Date From Daatabase " + (Date) query.uniqueResult());
    return (Date) query.uniqueResult();
}

From source file:kp.logic.GeneralMethods.java

public Date getSysDate() {
    Transaction tx = null;/*  ww w.  j a  v a 2 s  .  c  o  m*/
    Session session = null;
    Date date = null;
    try {
        session = HibernateUtil.getSessionFactory().openSession();
        tx = session.beginTransaction();
        SQLQuery query = session.createSQLQuery("select sysdate  from dual");
        Logger.getLogger(GeneralMethods.class.getName()).log(Level.SEVERE,
                "Date From Daatabase " + (Date) query.uniqueResult());
        date = (Date) query.uniqueResult();
    } catch (HibernateException ex) {
        if (tx != null) {
            tx.rollback();
        }
        Logger.getLogger(UserDao.class.getName()).log(Level.SEVERE, "Exception : {0}", ex);
        session.close();
    } finally {
        session.close();
    }
    return date;
}

From source file:lt.emasina.resthub.server.factory.DataFactory.java

License:Open Source License

public CcLob getLob(final Session session, final LobHandler handler) throws Exception {
    final Query q = handler.getQuery();
    final SQLQuery query = getPagedSQLQuery(session, handler);

    final MdColumn c = handler.getMdColumn();
    switch (c.getType()) {
    case BLOB://from  w  ww .j a  va2 s.  c o m
        query.addScalar(c.getName(), new WrapperBinaryType());
        break;
    case CLOB:
        query.addScalar(c.getName(), new TextType());
        break;
    default:
        throw new ClientErrorException(Status.CLIENT_ERROR_BAD_REQUEST,
                "Column %d (%s) expected to be LOB found %s", handler.getColumn(), c.getName(),
                c.getType().name());
    }

    if (log.isDebugEnabled()) {
        log.debug(query.getQueryString());
    }

    ExecutorService executor = Executors.newSingleThreadExecutor();
    Future<CcLob> fetchData = executor.submit(new Callable<CcLob>() {

        @Override
        @SuppressWarnings("unchecked")
        public CcLob call() throws Exception {
            CcLob cc = new CcLob();
            Object o = query.uniqueResult();
            if (o != null) {
                switch (c.getType()) {
                case CLOB:
                    cc.setValue((String) o);
                    break;
                case BLOB:
                    cc.setValue((Byte[]) o);
                    break;
                }
            }
            return cc;
        };
    });

    try {

        return fetchData.get(q.getTimeOut(), TimeUnit.SECONDS);

    } catch (ExecutionException | InterruptedException ex) {
        throw ex;
    } catch (TimeoutException ex) {
        throw new ServerErrorException(Status.SERVER_ERROR_GATEWAY_TIMEOUT, ex);
    }

}

From source file:lt.emasina.resthub.server.factory.DataFactory.java

License:Open Source License

public CcCount getCount(Session session, CountHandler handler) throws SQLException {
    final Query q = handler.getQuery();

    StringBuilder sb = new StringBuilder();
    sb.append("select count(*) from (").append(handler.getQuery().getSql()).append(") ");

    String sql = sb.toString();//ww w .  j ava2 s  .  c o m

    final SQLQuery query = session.createSQLQuery(sql);

    handler.applyParameters(query);
    if (log.isDebugEnabled()) {
        log.debug(query.getQueryString());
    }

    ExecutorService executor = Executors.newSingleThreadExecutor();
    Future<CcCount> func = executor.submit(new Callable<CcCount>() {

        @Override
        public CcCount call() throws Exception {
            CcCount cc = new CcCount();
            cc.setValue(((BigDecimal) query.uniqueResult()).longValue());
            return cc;
        }

    });

    try {

        return func.get(q.getTimeOut(), TimeUnit.SECONDS);

    } catch (ExecutionException | InterruptedException ex) {
        throw new ServerErrorException(Status.SERVER_ERROR_INTERNAL, ex);
    } catch (TimeoutException ex) {
        throw new ServerErrorException(Status.SERVER_ERROR_GATEWAY_TIMEOUT, ex);
    }
}

From source file:Metodos.Dao.java

public static String GetCarnet() {

        String consulta = "select getCarnet()";
        Session session = NewHibernateUtil.sessionFactory.openSession();
        SQLQuery consultaMysql = session.createSQLQuery(String.format(consulta));

        String value = consultaMysql.uniqueResult().toString();
        session.close();// w w w  .  ja v a 2  s.  com

        return value;
    }

From source file:Metodos.Dao.java

public static int idEstudiante(String carnet) {

        String consulta = "select count(*) " + "from Estudiante";
        Session session = NewHibernateUtil.sessionFactory.openSession();

        SQLQuery consultaMysql = session.createSQLQuery(String.format(consulta));
        int value = Integer.parseInt(consultaMysql.uniqueResult().toString());

        session.close();//from   w w  w .  jav  a 2  s.  c  o m

        return value;
    }

From source file:modelo.AbstractDAO.java

public int maxIndice(String tabla, String atributo) {
    SessionFactory factory;//from w  w  w . ja v  a 2s  .c  om
    try {
        factory = new Configuration().configure().buildSessionFactory();
    } catch (Throwable ex) {
        System.err.println("Failed to create sessionFactory object." + ex);
        throw new ExceptionInInitializerError(ex);
    }
    int max = -1;
    Session session = factory.openSession();
    Transaction tx = null;
    //System.out.println(max+1);
    try {
        tx = session.beginTransaction();
        String sql = "SELECT max(" + atributo + ") FROM " + tabla;
        SQLQuery query = session.createSQLQuery(sql);
        //System.out.println("hola"+sql);
        if (query.uniqueResult() != null) {
            max = (int) query.uniqueResult();
        }
        //System.out.println(max);
        tx.commit();
        //return max;
    } catch (HibernateException e) {
        System.out.println("coso" + e);

    } finally {
        session.close();
    }
    //System.out.println(max);
    return max + 1;
}

From source file:modelo.CalificacionLibroDAO.java

public Integer promedio(int id) {
    SessionFactory factory;/*from  w w  w  . j av  a2 s.  c o m*/
    Integer p = -1;
    try {
        factory = new Configuration().configure().buildSessionFactory();
    } catch (Throwable ex) {
        System.err.println("Failed to create sessionFactory object." + ex);
        throw new ExceptionInInitializerError(ex);
    }
    Session session = factory.openSession();
    Transaction tx = null;
    try {
        tx = session.beginTransaction();
        String sql = "SELECT avg(calificacion) FROM calificacionlibro WHERE libroidlibro =" + id;
        SQLQuery query = session.createSQLQuery(sql);
        if (query.uniqueResult() != null) {
            p = ((BigDecimal) query.uniqueResult()).intValue();
        }
        tx.commit();
        return p;
    } catch (HibernateException e) {
        if (tx != null)
            tx.rollback();
        return -1;
    } finally {
        session.close();
    }
}

From source file:modelo.CalificacionUsuarioDAO.java

public Usuario consumidor(int libro) {
    SessionFactory factory;/* w  ww  . j  a  v  a 2 s .  c  o m*/
    Usuario consumidor = null;
    try {
        factory = new Configuration().configure().buildSessionFactory();
    } catch (Throwable ex) {
        System.err.println("Failed to create sessionFactory object." + ex);
        throw new ExceptionInInitializerError(ex);
    }
    Session session = factory.openSession();
    Transaction tx = null;
    try {
        tx = session.beginTransaction();
        String sql = "SELECT * FROM usuario WHERE idusuario in (SELECT usridusuario FROM solicitudes WHERE libroidlibro ="
                + libro + "AND aceptado = TRUE)";
        SQLQuery query = session.createSQLQuery(sql);
        query.addEntity(Usuario.class);
        consumidor = (Usuario) query.uniqueResult();
        tx.commit();
        return consumidor;
    } catch (HibernateException e) {
        if (tx != null)
            tx.rollback();
        return null;
    } finally {
        session.close();
    }
}

From source file:modelo.CalificacionUsuarioDAO.java

public Integer promedio(int id) {
    SessionFactory factory;//w  ww  .j  a  va 2 s  . c o  m
    Integer p = -1;
    try {
        factory = new Configuration().configure().buildSessionFactory();
    } catch (Throwable ex) {
        System.err.println("Failed to create sessionFactory object." + ex);
        throw new ExceptionInInitializerError(ex);
    }
    Session session = factory.openSession();
    Transaction tx = null;
    try {
        tx = session.beginTransaction();
        String sql = "SELECT avg(calificacion) FROM calificacionusuario WHERE consumidoridusr in (SELECT usridusuario FROM solicitudes WHERE usridusuario ="
                + id + ")";
        SQLQuery query = session.createSQLQuery(sql);
        if (query.uniqueResult() != null) {
            p = ((BigDecimal) query.uniqueResult()).intValue();
        }
        tx.commit();
        return p;
    } catch (HibernateException e) {
        if (tx != null)
            tx.rollback();
        return -1;
    } finally {
        session.close();
    }
}