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:business.OpponentDB.java

public static Opponent findOpponent(int oppID) {
    SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
    Session session = null;//from  w w  w  .  j  ava  2 s .  co m
    Opponent opp = null;

    try {
        String qS = "FROM Opponent o WHERE o.id = :oppID";
        session = sessionFactory.openSession();
        Query q = session.createQuery(qS);
        q.setParameter("oppID", oppID);
        opp = (Opponent) q.uniqueResult();
    } catch (NoResultException e) {
        return null;
    } finally {
        if (session != null && session.isOpen()) {
            session.close();
        }
    }

    return opp;
}

From source file:businesslayer.Application.java

public void updateAttendence() {

    Scanner in = new Scanner(System.in);
    try {//from   w ww.ja  v a2  s. com
        Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        System.out.println("Enter roll no of student");
        String rollNo = in.nextLine();// Get roll no from user

        Query q = session.createQuery("from Attendance a where a.student=" + rollNo);
        Attendance a = (Attendance) q.uniqueResult();
        a.setIsPresent(true);
        session.getTransaction().commit();

    } catch (HibernateException he) {
        he.printStackTrace();
    }
}

From source file:BusinessServices.AccountService.java

public TblAccount searchAccount(String pi_Id)
{
      //String message=null;
    Session session=null;/*  w  ww. j a va2s .co m*/
   Transaction tx = null;
TblAccount account = null;
try {
             session=NewHibernateUtil.getSessionFactory().openSession();
   tx = session.getTransaction();
   tx.begin();
   Query query = session.createQuery("from TblAccount where accountId='"+pi_Id+"'");
   account = (TblAccount)query.uniqueResult();
   tx.commit();
} catch (Exception e) {
   if (tx != null) {
      tx.rollback();
   }
   e.printStackTrace();
} finally {
   session.close();
}
return account;
}

From source file:ca.myewb.controllers.home.Search.java

License:Open Source License

private int numMatchingSearchables(HashMap<String, String> terms) {
    String sql = "select count(*) " + getCommonQueryPart(terms);

    Query query = hibernateSession.createSQLQuery(sql).setString("terms", terms.get("Body"));

    if (!terms.get("Since").equals(""))
        query.setString("since", terms.get("Since"));

    return ((BigInteger) query.uniqueResult()).intValue();
}

From source file:cc.cnfc.core.orm.hibernate.HibernateDao.java

License:Open Source License

/**
 * ??HQL??//from   www  . ja  va 2s  .c  o  m
 *
 *  1?? a)?(MySQL,Oracle,SQL
 * Server2005)?limit n,m b)?(informix,Sybase 12.5.3,SQL
 * Server)?top n c)???? 2?
 * 3?order bygroup by,having  Query q= session.createQuery(
 * "select new A(M.a,N.b) from M as M,N as N where M.id=N.id");
 *
 * @param hql
 *            HQL??Where???select???? select
 *            a,b,(select c from table1) as d from table2 ...
 *            1)(select *)??from TUser
 *            2)select userName,password from TUser;
 * @param propertyNames
 *            ???
 * @param operators
 *            ????=???null
 *            ???=, >=, <=, <>, !=, like
 * @param values
 *            ?
 * @param offset
 *            0??-1
 * @param size
 *            ??-1
 * @param isTotalSize
 *            ??true
 * @param orderBy
 *            ?,??order byorderBy="a desc,b asc",??order by a
 *            desc,b asc
 * @param groupBy
 *            ,??group by groupBy="a desc,b asc",??group by a
 *            desc,b asc
 * @param otherCause
 *            where????(order by),(group by)??(having)
 * @param isCache
 *            ?cache "group by name order by name desc"
 * @return Object[] List list = (List)Object[0]
 *         int count = ((Integer)Object[1]).intValue;
 * @throws com.rwy.base.core.exception.GenericException
 * 
 */
public Object[] query(final String hql, final String[] propertyNames, final String[] operators,
        final Object[] values, final int offset, final int size, final boolean isTotalSize,
        final String orderBy, final String groupBy, final String otherCause, final boolean isCache)
        throws DataAccessException {
    Assert.hasText(hql, "hql?");

    Query query;
    String countSql;
    String fullSql;
    Integer count = 0;
    Map map = new HashMap();
    String where = "";

    if (propertyNames != null && propertyNames.length > 0 && values != null && values.length > 0) {
        if (propertyNames.length != values.length) {
            throw new GenericException();
        }

        if (operators != null && propertyNames.length != operators.length) {
            logger.error("");
            throw new GenericException();
        }

        for (int i = 0; i <= propertyNames.length - 1; i++) {
            if ("".equals(where)) {
                where = " where ";
            } else {
                where += "and ";
            }
            if (operators != null && operators[i].equalsIgnoreCase("isnull")) {
                where += propertyNames[i] + " is null ";
            } else if (operators != null && operators[i].equalsIgnoreCase("isnotnull")) {
                where += propertyNames[i] + " is not null ";
            } else if (operators != null && operators[i].equalsIgnoreCase("isempty")) {
                where += propertyNames[i] + " = '' ";
            } else if (operators != null && operators[i].equalsIgnoreCase("isnotempty")) {
                where += propertyNames[i] + " <> '' ";
            } else if (operators != null && operators[i].equalsIgnoreCase("in")) {
                where += propertyNames[i] + " in ";
            } else {
                where += propertyNames[i]
                        + (operators == null || operators[i] == null ? "=" : " " + operators[i]) + " ? ";
            }
        }

        fullSql = hql + where;
        fullSql += otherCause == null || otherCause.trim().equals("") ? "" : " " + otherCause;

        fullSql += groupBy == null || groupBy.trim().equals("") ? "" : " group by " + groupBy;
        fullSql += orderBy == null || orderBy.trim().equals("") ? "" : " order by " + orderBy;

        query = isCache ? this.createQuery(fullSql).setCacheable(true) : this.createQuery(fullSql);

        int paramIndex = 0;
        for (int i = 0; i <= values.length - 1; i++) {
            if (operators != null && operators[i].equalsIgnoreCase("isnull"))
                continue;
            if (operators != null && operators[i].equalsIgnoreCase("isnotnull"))
                continue;
            if (operators != null && operators[i].equalsIgnoreCase("isempty"))
                continue;
            if (operators != null && operators[i].equalsIgnoreCase("isnotempty"))
                continue;
            // IN?
            if (operators != null && operators[i].equalsIgnoreCase("in")) {
                values[i] = StringUtil.getInString(values[i]);
            }
            query.setParameter(paramIndex++, values[i]);
        }

    } else {
        if ("".equals(where) && hql.indexOf("where") == -1) {
            where = " where 1=1 ";
        } else if (!"".equals(where)) {
            where += " and ";
        }

        fullSql = hql + where;
        fullSql += otherCause == null || otherCause.trim().equals("") ? "" : " " + otherCause;

        fullSql += groupBy == null || groupBy.trim().equals("") ? "" : " group by " + groupBy;
        fullSql += orderBy == null || orderBy.trim().equals("") ? "" : " order by " + orderBy;

        query = this.createQuery(fullSql);
    }

    // ?
    if (isTotalSize) {

        // ???order by ???
        countSql = hql + where;

        // modi by hongdj

        countSql += groupBy == null || groupBy.trim().equals("") ? "" : " group by " + groupBy;
        countSql += otherCause == null || otherCause.trim().equals("") ? "" : " " + otherCause;

        // ?hql?hql??select????
        // select a,b,(select c from table1) as d from table2 ...
        countSql = "select count(*) from " + countSql.substring(countSql.toLowerCase().indexOf("from") + 5);
        Query query2 = this.createQuery(countSql);

        int paramIndex = 0;
        if (values != null) {
            for (int i = 0; i <= values.length - 1; i++) {
                if (operators != null && operators[i].equalsIgnoreCase("isnull"))
                    continue;
                if (operators != null && operators[i].equalsIgnoreCase("isnotnull"))
                    continue;
                if (operators != null && operators[i].equalsIgnoreCase("isempty"))
                    continue;
                if (operators != null && operators[i].equalsIgnoreCase("isnotempty"))
                    continue;
                query2.setParameter(paramIndex++, values[i]);
            }
        }
        // modi by denny
        Long res = (Long) query2.uniqueResult();
        if (res != null) {
            count = res.intValue();
        }
    }

    if (offset > 0) {
        query.setFirstResult(offset);
    }

    if (size > 0) {
        query.setMaxResults(size);
    }

    // ?log
    // logger.debug("fullSql=" + query.getQueryString());

    map.put("list", query.list());
    map.put("count", count);
    return new Object[] { map.get("list"), map.get("count") };
}

From source file:cc.cnfc.core.service.BaseService.java

License:Open Source License

/**
 * ???/*from  w  w w  .  j a va  2 s. c  o m*/
 * 
 * @param object
 *            ?hibernate entity instance
 * @param propertyName
 *            ??
 * @param propertyValue
 *            
 * @param idValue
 *            ID
 */
@Transactional(propagation = Propagation.SUPPORTS)
protected int checkPropertyExist(Object object, String propertyName, Serializable propertyValue,
        Serializable idValue) {
    StringBuilder sb = new StringBuilder("SELECT COUNT(*) FROM ");
    sb.append(object.getClass().getSimpleName()).append(" WHERE ");
    sb.append(propertyName).append(" = :propertyValue");
    if (idValue != null) {
        sb.append(" AND ").append(this.getIdName(object.getClass()));
        sb.append(" <> :idValue");
    }
    Map<String, Object> paramMap = new HashMap<String, Object>();
    paramMap.put("propertyValue", propertyValue);
    paramMap.put("idValue", idValue);
    Query q = hibernateDao.createQuery(sb.toString(), paramMap);
    // hib3.2JPAuniqueResult Long
    return ((Number) q.uniqueResult()).intValue();
}

From source file:cdp.InicializarAgente.java

public static InicializarAgente obterIA(int idIni) {
    Session sessao = HibernateUtility.getSession(); //Abrindo uma sessao
    Transaction transacao = sessao.beginTransaction(); //Iniciando uma transacao

    Query select = sessao.getNamedQuery("BuscarIA");
    select.setInteger("idIni", idIni);

    InicializarAgente ia = new InicializarAgente();
    ia = (InicializarAgente) select.uniqueResult();

    transacao.commit(); //Finalizando a transacao
    sessao.close(); //Fechando a sessao

    return ia;//w w  w  .j a v a2 s.com
}

From source file:cdp.InicializarAgenteVariaveis.java

public static InicializarAgenteVariaveis obterIAV(int idIni, int idVar) {
    Session sessao = HibernateUtility.getSession(); //Abrindo uma sessao
    Transaction transacao = sessao.beginTransaction(); //Iniciando uma transacao

    Query select = sessao.getNamedQuery("BuscarIAV");
    select.setInteger("idIni", idIni);
    select.setInteger("idVar", idVar);

    InicializarAgenteVariaveis iav = new InicializarAgenteVariaveis();
    iav = (InicializarAgenteVariaveis) select.uniqueResult();

    transacao.commit(); //Finalizando a transacao
    sessao.close(); //Fechando a sessao

    return iav;/*from w  w w .  j a  va2 s  .c om*/
}

From source file:celepsa.rrcc.da.ClimaDA.java

public int CriticidadZona(Tmzona objSistema) throws Exception {
    logger.debug("eliminarAgrupacion id=" + objSistema.getId());
    String sQuery = " SELECT tmZona.id as zona_id, tmZona.Descripcion,"
            + " SUm( tmTipoDocumento.Criticidad_id) as sumCri "
            + "FROM tmDocumento, tmTipoDocumento, tmStakePersona, tmZona "
            + "where tmDocumento.eliminado = 0 and "
            + "tmDocumento.tmEstado_id = 1 and tmDocumento.tmTipoDocumento_id <>0 "
            + "and tmDocumento.tmTipoDocumento_id = tmTipoDocumento.id "
            + "and tmDocumento.tmStakePersona_id = tmStakePersona.id "
            + "and tmStakePersona.tmZona_id =tmZona.id " + "and tmZona.id='" + objSistema.getId() + "'";
    try {//from  w ww.j a  v  a2  s  . co m
        org.hibernate.Transaction tx = session.beginTransaction();
        Query query = session.createSQLQuery(sQuery);
        Integer res = (Integer) query.uniqueResult();
        if (res != null) {
            setSumCri(res);
        } else {
            setSumCri(0);
        }
        tx.commit();
        return getSumCri();
    } catch (NumberFormatException | HibernateException e) {
        logger.error(e.getMessage());
        throw e;
    }
}

From source file:celepsa.rrcc.da.ClimaDA.java

public int InfluenciaPersonas(Tmzona objSistema) throws Exception {
    logger.debug("eliminarAgrupacion id=" + objSistema.getId());
    String sQuery = "select tmStakePersona.tmZona_id, SUM(tmStakePersona.tmNivelInfluencia_id) as SumNin "
            + "from tmStakePersona,tmNivelInfluencia " + "where tmStakePersona.tmZona_id='" + objSistema.getId()
            + "' and " + "tmStakePersona.tmNivelInfluencia_id=tmNivelInfluencia.id ";
    try {// w w w .  j  ava 2 s . co  m
        org.hibernate.Transaction tx = session.beginTransaction();
        Query query = session.createSQLQuery(sQuery);
        Integer res = (Integer) query.uniqueResult();
        if (res != null) {
            setSumInf(res);
        } else {
            setSumInf(0);
        }
        tx.commit();
        return getSumInf();
    } catch (NumberFormatException | HibernateException e) {
        logger.error(e.getMessage());
        throw e;
    }
}