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:org.generationcp.middleware.dao.ProjectUserRoleDAO.java

License:Open Source License

/**
 * Returns the number of {@link User} records associated with a {@link Project}
 *
 * @param projectId - the project id/*  www .  ja v a  2s . co m*/
 * @return the number of {@link User} records
 * @throws MiddlewareQueryException the MiddlewareQueryException
 */
public long countUsersByProjectId(Long projectId) throws MiddlewareQueryException {
    try {
        SQLQuery query = getSession().createSQLQuery(ProjectUserRole.COUNT_USERS_BY_PROJECT_ID);
        query.setParameter("projectId", projectId);
        return ((BigInteger) query.uniqueResult()).longValue();
    } catch (HibernateException e) {
        throw new MiddlewareQueryException("Error in countUsersByProjectId(projectId=" + projectId
                + ") query from ProjectUser: " + e.getMessage(), e);
    }
}

From source file:org.generationcp.middleware.dao.StudyDAO.java

License:Open Source License

public long countBySeason(Season season) throws MiddlewareQueryException {
    try {// w w w.  j av a 2 s  .  co  m
        SQLQuery query = getSession().createSQLQuery(Study.COUNT_BY_SEASON);

        if (season == Season.DRY) {
            query = getSession().createSQLQuery(Study.COUNT_BY_SEASON + Study.DRY_SEASON_CONDITION);
        } else if (season == Season.WET) {
            query = getSession().createSQLQuery(Study.COUNT_BY_SEASON + Study.WET_SEASON_CONDITION);
        }

        return ((BigInteger) query.uniqueResult()).longValue();

    } catch (HibernateException e) {
        throw new MiddlewareQueryException(
                "Error with countBySeason(season=" + season + ") query from Study: " + e.getMessage(), e);
    }

}

From source file:org.glite.security.voms.admin.persistence.deployer.FixMissingIndexesOnAuditTable.java

License:Apache License

@Override
public void run() {

    LOG.info("Checking indexes on audit_event table...");

    ResultSet rs = null;//from   ww w  .ja v  a  2  s  .  c om

    try {
        GetCatalogWork gcw = new GetCatalogWork();
        session.doWork(gcw);

        String dbName = gcw.getCatalogName();

        LOG.info("Database name: {}", dbName);

        String checkIndexQuery = String.format("select count(index_name) from information_schema.statistics "
                + "where table_schema = '%s' and table_name = 'audit_event' "
                + "and column_name = 'event_timestamp'", dbName);

        SQLQuery q = session.createSQLQuery(checkIndexQuery);

        BigInteger indexCount = (BigInteger) q.uniqueResult();

        LOG.info("indexCount: {}", indexCount);

        if (indexCount.intValue() == 0) {
            createIndexes();
        } else if (indexCount.intValue() == 2) {
            LOG.info("Indexes found on audit_event, no action required.");
            return;
        } else {
            throw new VOMSException(
                    "Invalid schema configuration: audit_event table has an invalid number of indexes: "
                            + indexCount);
        }

    } catch (SQLException e) {
        LOG.error("SQL error: " + e.getMessage(), e);
        throw new VOMSException(e);

    } finally {
        safeCloseResultSet(rs);
    }

}

From source file:org.hil.core.dao.hibernate.ChildrenDaoHibernate.java

License:Open Source License

public long checkDuplicate(Children child) {
    String sql = "Select count(*) from children c, village vl "
            + " where c.id_village =vl.id and vl.id_commune=:communeId "
            + " and YEAR(c.date_of_birth)=:yob and c.mother_name =:motherName ";
    SQLQuery qry = getSession().createSQLQuery(sql);
    qry.setParameter("communeId", child.getVillage().getCommune().getId());
    int yob = child.getDateOfBirth().getYear() + 1900;
    qry.setParameter("yob", yob);
    qry.setParameter("motherName", child.getMotherName());
    log.debug("SQL: " + sql);
    long result = ((Number) qry.uniqueResult()).longValue();
    log.debug(result);/*  www .j  a v  a 2s . c  om*/
    return result;
}

From source file:org.hil.core.dao.hibernate.ChildrenVaccinationHistoryDaoHibernate.java

License:Open Source License

public boolean checkFinish(Children child) {
    String sql = "Select count(*) from children_vaccination_history cvh "
            + " where cvh.id_children =:childId and cvh.vaccinated=:vaccinated and id_vaccination in ('2','3','4','5','6','7','8','9') ";
    SQLQuery qry = getSession().createSQLQuery(sql);
    qry.setParameter("vaccinated", 1);
    qry.setParameter("childId", child.getId());
    log.debug("SQL: " + sql);
    long result = ((Number) qry.uniqueResult()).longValue();
    log.debug(result);//  ww w. j a  v a  2 s  .com
    if (result == 8)
        return true;
    else
        return false;
}

From source file:org.hil.core.dao.hibernate.ChildrenVaccinationHistoryDaoHibernate.java

License:Open Source License

public Date checkFinishDate(Children child) {
    String sql = "Select max(cvh.date_of_immunization) from children_vaccination_history cvh "
            + " where cvh.id_children =:childId and cvh.vaccinated=:vaccinated and id_vaccination in ('2','3','4','5','6','7','8','9') ";
    SQLQuery qry = getSession().createSQLQuery(sql);
    qry.setParameter("vaccinated", 1);
    qry.setParameter("childId", child.getId());
    log.debug("SQL: " + sql);
    Date result = ((Date) qry.uniqueResult());
    log.debug(result);/*from  w w  w.  j ava2  s .  co m*/
    return result;
}

From source file:org.jbpm.test.Db.java

License:Open Source License

public static String verifyClean(ProcessEngine processEngine) {
    SessionFactory sessionFactory = processEngine.get(SessionFactory.class);
    // when running this with a remote ejb invocation configuration, there is no
    // session factory and no cleanup needs to be done
    if (sessionFactory == null) {
        return null;
    }/*from w  ww.  j  a  v a2  s.  c o m*/

    String[] tableNames = tableNamesCache.get(processEngine);

    if (tableNames == null) {
        Configuration configuration = processEngine.get(Configuration.class);

        // loop over all foreign key constraints
        List<String> tableNamesList = new ArrayList<String>();
        Iterator iter = configuration.getTableMappings();
        while (iter.hasNext()) {
            Table table = (Table) iter.next();
            if (table.isPhysicalTable()) {
                tableNamesList.add(table.getName());
            }
        }

        tableNames = tableNamesList.toArray(new String[tableNamesList.size()]);

        tableNamesCache.put(processEngine, tableNames);
    }

    String recordsLeftMsg = "";
    Session session = sessionFactory.openSession();
    try {
        for (String tableName : tableNames) {
            String countSql = "select count(*) as RECORD_COUNT_ from " + tableName;
            SQLQuery sqlQuery = session.createSQLQuery(countSql);
            sqlQuery.addScalar("RECORD_COUNT_", Hibernate.LONG);
            Long recordCount = (Long) sqlQuery.uniqueResult();
            if (recordCount > 0L) {
                recordsLeftMsg += tableName + ":" + recordCount + ", ";
            }
        }
    } finally {
        session.close();
    }

    if (recordsLeftMsg.length() > 0) {
        clean(processEngine);
    }

    return recordsLeftMsg;
}

From source file:org.jpos.ee.pm.core.monitor.SQLMonitorSource.java

License:Open Source License

public MonitorLine getLastLine() throws Exception {
    MonitorLine result = new MonitorLine();
    DB db = new DB();
    db.open();//ww  w .  j av  a 2s  .  c o m
    try {
        SQLQuery c = db.session().createSQLQuery(getLastLineQuery().trim());
        c.setMaxResults(1);
        Object item = c.uniqueResult();
        if (item instanceof Object[]) {
            Object[] objects = (Object[]) item;
            result.setId(objects[getIdColumn()]);
            result.setValue(objects);
        } else {
            result.setId(item);
            Object[] objects = { item };
            result.setValue(objects);
        }
    } finally {
        db.close();
    }
    return result;
}

From source file:org.ktunaxa.referral.server.service.ResetReferralCounterService.java

License:Open Source License

@SuppressWarnings("rawtypes")
@Override/*from   www  . ja  va  2s.co  m*/
public boolean onPreInsert(PreInsertEvent event) {
    Object object = event.getEntity();
    if (object instanceof Referral) {
        // using the current session causes flush, followed by rg.hibernate.AssertionFailure: null id in
        // org.ktunaxa.referral.server.domain.Referral entry ?!!
        Session session = sessionFactoryImpl.openSession();
        try {
            SQLQuery q1 = session.createSQLQuery("SELECT count(*) as cnt, to_char(current_date, 'yyyy') as yr "
                    + "FROM referral WHERE calendar_year = cast(to_char(current_date, 'yy')" + " as integer)")
                    .addScalar("cnt", new IntegerType()).addScalar("yr", new StringType());
            Object[] result = (Object[]) q1.uniqueResult();
            Integer cnt = (Integer) result[0];
            String yr = (String) result[1];
            log.info("Found " + cnt + " referrals for the current year " + yr);
            if (cnt == 0) {
                log.info("No referrals found for the current year " + yr
                        + ", resetting sequence before adding the first referral");
                // in the (unlikely) case that multiple referrals are committed concurrently,
                // this may cause loss of one or more concurrent referrals because of duplicate key errors
                session.createSQLQuery("select setval('referral_number_seq',1,false)");
            }
        } finally {
            session.close();
        }
    }
    return false;
}

From source file:org.openmrs.api.db.hibernate.HibernateConceptDAO.java

License:Mozilla Public License

/**
 * @see org.openmrs.api.db.ConceptDAO#getSavedConceptDatatype(org.openmrs.Concept)
 *///from  w w  w .ja v  a2  s. co  m
public ConceptDatatype getSavedConceptDatatype(Concept concept) {
    SQLQuery sql = sessionFactory.getCurrentSession()
            .createSQLQuery("select datatype.* from " + "concept_datatype datatype, " + "concept concept "
                    + "where " + "datatype.concept_datatype_id = concept.datatype_id "
                    + "and concept.concept_id=:conceptId")
            .addEntity(ConceptDatatype.class);
    sql.setInteger("conceptId", concept.getConceptId());
    return (ConceptDatatype) sql.uniqueResult();
}